思路:
在写的时候遇到一个问题:就是当‘A’‘B’‘C’都行不通的时候就要返回上一层,如果上一层的‘A’‘B’‘C’也试了还不行,就要删除最后一个字符重新选择,但又不好写回溯条件。那么这道题到底需不需要回溯呢?我从网上看到了一句话是解释什么时候回溯什么时候不回溯,我觉得说的特别有道理,一下子让我豁然开朗。
要不增值就在递归的参数里面加,要不就回溯
#include#include using namespace std; int n,L; bool isHard(string s,char c){ int j = 1; for(int i = s.length() - 1; i >= 0; i-=2){ string s1 = s.substr(i, j); string s2 = s.substr(i + j) + c; if(!s1.compare(s2)){ return false; } j++; } return true; } void dfs(int cnt, string s){ if(cnt == n){ cout << s; exit(0); } for(char i = 'A'; i < 'A' + L; i++){ if(isHard(s,i)){//如果组合起来是困难的串就继续纵向递归 dfs(cnt+1, s+i); } } } int main(){ cin >> n >> L; dfs(0, ""); return 0; }



