使用DFS生成全排列

 1 #include <string>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <iostream>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8 
 9 // 使用DFS深度优先搜索生成全排列
10 // 如果当前生成的排列满足条件(逻辑意义上的有序),返回true
11 bool dfs(string &bunch, int bLen, string str) {
12     if (bLen == str.length()) {
13             // 
14     }
15     
16     string::size_type i;
17     for (i = 0; i < bLen; ++i) {
18         if (!vis[i]) {
19             vis[i] = true;
20             str += bunch[i];
21             if (dfs(bunch, bLen, str)) {
22                 return true;
23             }
24             vis[i] = false;
25             str = str.substr(0, str.length() - 1);
26         }
27     }// End of for
28     return false;
29 }
30 
31 int main() {
32     string bunch;
33     
34     while (cin >> bunch) {
35         dfs(bunch, bunch.length(), "");
36     }// End of while
37     return 0;
38 }


方法二:使用STL中的next_permutation生成

 1 #include <string>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <iostream>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8 
 9 string res;
10 
11 int main() {
12     string bunch;
13     
14     while (cin >> bunch) {
15         sort(bunch.begin(), bunch.end());
16         do {
17             cout << bunch << endl;
18         } while (next_permutation(bunch.begin(), bunch.end()));
19     }// End of while
20     return 0;
21 }


 

posted @ 2012-12-08 19:25  Maxwell:My Blog  阅读(1169)  评论(0编辑  收藏  举报