//转载请注明出处:http://www.cnblogs.com/zhishoumuguinian/p/8683527.html
1 #include<bits/stdc++.h> 2 3 using namespace std; 4 5 int visited[100]={0}; 6 int a[100]; 7 int k; 8 void permutation(int n) 9 { 10 if(n==k) 11 { 12 for(int j=0; j<k; j++) 13 { 14 cout<<a[j]; 15 } 16 cout<<endl; 17 return ; 18 } 19 for(int i=1; i<=k; i++) 20 { 21 if(visited[i]==0) 22 { 23 a[n]=i; 24 visited[i]=1; 25 permutation(n+1); 26 visited[i]=0; 27 } 28 } 29 } 30 31 32 int main() 33 { 34 cin>>k; 35 permutation(0); 36 }
STL
1 #include<bits/stdc++.h> 2 using namespace std; 3 char a[100]; 4 int length; 5 int main() 6 { 7 cin>>a; 8 length=strlen(a); 9 do 10 { 11 cout<<a<<endl; 12 }while(next_permutation(a,a+length)); 13 }
深度优先搜索
1 #include<bits/stdc++.h> 2 using namespace std; 3 int visited[100]; 4 int Array[100]={0}; 5 char a[100]; 6 int n; 7 void Permutation(int num) 8 { 9 if(num==n) 10 { 11 for(int j=0; j<n; j++) 12 { 13 cout<<a[Array[j]-1]; 14 } 15 cout<<endl; 16 return; 17 } 18 for(int i=1; i<=n; i++) 19 { 20 if(visited[i]==0) 21 { 22 visited[i]=1; 23 Array[num++]=i; 24 Permutation(num); 25 visited[i]=0; 26 num--; 27 } 28 29 } 30 31 } 32 33 34 int main() 35 { 36 cin>>a; 37 n=strlen(a); 38 Permutation(0); 39 }