鼓励篇:这个类型的题目真的写的越多越有感觉,从一无所知到朦朦胧胧再到一看就知道用这个法子,这种思维的成长就像学数学一样
来源:https://www.nowcoder.com/practice/5632c23d0d654aecbc9315d1720421c1?tpId=61&tqId=29515&tPage=1&ru=/kaoyan/retest/1002&qru=/ta/pku-kaoyan/question-ranking
是参考大神的代码才知道dfs可以用
#include<stdio.h> #include<iostream> #include<string.h> using namespace std; char str[10]; char res[10]; int visit[10]={0}; void dfs(int depth){ if(depth==strlen(str)){ printf("%s\n",res); } else{ for(int i=0;i<strlen(str);i++){ if(visit[i]==0){ visit[i]=1; res[depth]=str[i]; dfs(depth+1); visit[i]=0; } } } } int main(void){ while(cin>>str){ int len=strlen(str); dfs(0); } return 0; }
来源:https://www.nowcoder.com/practice/7cf7b0706d7e4b439481f53e5fdac6e7?tpId=62&tqId=29460&tPage=1&rp=1&ru=/ta/sju-kaoyan 这道题的递归写法没想到,对于这种字符串输出很不熟 #include<stdio.h> #include<string.h> #include<iostream> using namespace std; void dfs(int n){ int binary[20]={0}; int tmp_n=n; int bin_size=0; while(tmp_n>0){ binary[bin_size++]=tmp_n%2; tmp_n/=2; } bool first=true; for(int i=bin_size-1;i>=0;i--){ if(binary[i]==1){ if(!first){ cout<<"+"; } first=false; if(i==0){ cout<<"2(0)"; } else if(i==1){ cout<<"2"; } else{ cout<<"2("; dfs(i); cout<<")"; } } } } int main(void){ int n; while(scanf("%d",&n)!=EOF){ dfs(n); printf("\n"); } return 0; }
八皇后问题(来自网上大神的)#include<stdio.h>#include<vector>
#include<iostream> #include<algorithm> using namespace std; const int MAX=100000; //eye1:主对角线(x+n-y是定值), eye2:次对角线(x+y定值) long long row[MAX],col[MAX],eye1[MAX*3],eye2[MAX*3],n=8,res=0,b; vector<string>v; //对第x行进行搜索 void dfs(long long x,string s){ if(x==n+1){ res++; v.push_back(s); return; } for(int i=1;i<=n;i++){ if(!row[x]&&!col[i]&&!eye1[x+n-i]&&!eye2[x+i]){ row[x]=col[i]=eye1[x+n-i]=eye2[x+i]=1; s+=i+'0'; dfs(x+1,s);//x行有了皇后,继续下一行
//回溯
s.erase(s.end()-1); row[x]=col[i]=eye1[x+n-i]=eye2[x+i]=0; } } } int main(void){ int b; while(cin>>b){ res=0; string s; v.clear(); dfs(1,s); sort(v.begin(),v.end()); cout<<v[b-1]<<endl; } return 0; }