打印长度为p的,可以从给定的集合来形成的所有可能的串 [英] print all possible strings of length p that can be formed from the given set

查看:100
本文介绍了打印长度为p的,可以从给定的集合来形成的所有可能的串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一组的字符和正整数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

这篇关于打印长度为p的,可以从给定的集合来形成的所有可能的串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆