I want to generate all the strings of length from 1 to 10 by only words '4' and '7' in sorted order
example-> 1)4 //first string
2)7 //second string
3)44 //third,because next after 7 should be 44
4)47 //fourth,after 44
. . .
. . .
. . .
This way till length <=10
I tried myself and my backtracking code looks something like this
#include<bits/stdc++.h>
using namespace std;
vector<string>v; // for storing intermediate string in backtracking
void generate(string s,char ch)
{
if(s.length()>=9)return; //length > 10 returning
s+=ch; //adding to string a new character
v.push_back(s); //storing strings
generate(s,'4'); //first backtracking
generate(s,'7'); //second backtracking
}
int main()
{
generate("",'4');
sort(v.begin(),v.end()); //sorting to get ascending order string
string thisfind; //to find postion of string thisfind in vector...like postion of '4' is 1
cin>>thisfind;
int l=find(v.begin(),v.end(),thisfind)-v.begin(); //just usual find function
cout<<l+1<<endl; //output
return 0;
}
This is not correct please propose a backtracking algorithm to do the same
Note:- No worries of time-complexity