我想按排序顺序仅通过单词“4”和“7”生成长度从 1 到 10 的所有字符串
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
我试过了,我的回溯代码看起来像这样
#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;
}
这是不正确的,请提出一个回溯算法来做同样的事情
注意:- 不用担心时间复杂性