(Repetitive numbers allowed "for loop recursion " )Print all possible strings of length k that can be formed from a set of n characters

Input: 
set[] = {'a', 'b'}, k = 3

Output:
aaa
aab
aba
abb
baa
bab
bba
bbb


Input: 
set[] = {'a', 'b', 'c', 'd'}, k = 1
Output:
a
b
c
d

This is a "branch and bound" type of Recursion in which we have to choose whether to "take a no." or  "not to take" that number . Here Repetition is allowed ,therefore a "for loop" is needed.





#include<bits/stdc++.h>

using namespace std;
set<vector<char> > s;
void gen(char a[],int n,int k,int cnt,vector<char> v,int j)
{
    if(cnt==k)
    {
     s.insert(v);
    }

    if(j>=n)
        return;

    for(int i=0;i<n;i++)
    {
        gen(a,n,k,cnt,v,j+1);
        v.push_back(a[i]);
        gen(a,n,k,cnt+1,v,j+1);
        v.pop_back();
    }
}


int main()
{
 char a[]={'a','b','c','d'};
 int n,k;
 cin>>n>>k;
 vector<char> v;
 gen(a,n,k,0,v,0);

set<vector<char> > ::iterator i;
 for(i=s.begin();i!=s.end();i++)
 {
     v=*i;
     for(int j=0;j<v.size();j++)
        cout<<v[j]<<" ";
         cout<<endl;
 }


 return  0;
}

Comments

Popular posts from this blog

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.