51Nod 1384 全排列

 1 #include <iostream>
 2 #include <cmath>
 3 #include <string>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <map>
 7 using namespace std;
 8 
 9 char s[50];
10 
11 bool cmp(char x,char y){
12     return x < y;
13 }
14 
15 int main(){
16     cin >> s;
17     int len = strlen(s);
18     sort(s, s+len, cmp);
19     //cout << s<< endl;
20     do{
21         cout<<s<< endl;
22     }
23     while(next_permutation(s,s+len));
24     return 0;
25 }

回溯:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 char s[20];
 7 int book[30],a[20],ans[20],n;
 8 
 9 void dfs(int dis,int cnt)
10 {
11     int i,j;
12     if(cnt==n) {
13         for(i=1;i<=n;i++) cout<<ans[i];
14         cout<<endl;
15         return;
16     } 
17     for(i=dis;i<n;i++) {
18         if(book[i]==0) {
19             book[i]=1;
20             ans[cnt+1]=a[i];
21             dfs(dis,cnt+1);
22             book[i]=0;
23             while(i<n && a[i]==a[i+1]) i++;
24         }
25     }
26     
27 }
28 
29 
30 int main()
31 {
32      ios::sync_with_stdio(false);  
33     int i,j;
34     cin>>s;
35     n=strlen(s);
36     for(i=0;i<n;i++) a[i]=s[i]-'0';
37     sort(a,a+n);
38     dfs(0,0);
39     return 0;
40 } 
原文地址:https://www.cnblogs.com/ouyang_wsgwz/p/9013023.html