给定一组的字符和正整数p,我必须打印长度为P的,可以从给定的集合来形成的所有可能的字符串
Given a set of characters and a positive integer p, I have to print all possible strings of length p that can be formed from the given set.
for eg: if the set is {a,b}
and the value of p is 2
Output is: aa,ab,ba,bb
我知道,对于一个给定大小为n,还有将为n P 长度P的可能的字符串。
I know that for a given set of size n, there will be np possible strings of length p.
什么是可用于打印的所有可能的串的最佳方法。?我只是想一个办法来解决。
What is the best method that can be used to print all the possible strings.? I just want an approach to solve.
我用C。
一个可能的办法是从空字符串开始和一个使用递归函数并打印其添加的人物之一吧。
A possible approach could be to start from an empty string and add characters one by one to it using a recursive function and printing it.
下面是我的code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void print_string(char str[],char new_str[],int current_len,int n,int len)
{
/*
str=orignal set,
new_str=empty char array,
current_len=0(Intially)
n=no of elements to be used
len=the value of p given*/
if(current_len==len)//print string when length is equal to p
{
printf("%s\n",new_str);
return;
}
else
{
int i;
for(i=0;i<n;i++)
{
new_str[current_len]=str[i];
print_string(str,new_str,current_len+1,n,len);
}
}
}
int main()
{
char set[]={'a','b'};
char arr[10]="";
print_string(set,arr,0,2,2);
return 0;
}
输出:
aa
ab
ba
bb