File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ /* ************************************************************************
2+ > File Name: permu.cpp
3+ > Author: wangxiaoxian
4+ 5+ > Created Time: Wed 03 Aug 2016 10:14:19 PM CST
6+ ************************************************************************/
7+ // 返回一个字符串所有的排列方式
8+ // 代码来自:http://www.cricode.com/624.html
9+
10+ #include < iostream>
11+ #include < vector>
12+ using namespace std ;
13+
14+ typedef vector<string> vs;
15+
16+ vs permu (string s){
17+ vs result;
18+ if (s == " " ){
19+ result.push_back (" " );
20+ return result;
21+ }
22+ string c = s.substr (0 , 1 );
23+ vs res = permu (s.substr (1 ));
24+ for (int i=0 ; i<res.size (); ++i){
25+ string t = res[i];
26+ for (int j=0 ; j<=t.length (); ++j){
27+ string u = t;
28+ u.insert (j, c);
29+ result.push_back (u);
30+ }
31+ }
32+
33+ return result; // 调用result的拷贝构造函数,返回它的一份copy,然后这个局部变量销毁(与基本类型一样)
34+ }
35+
36+ vs permu1 (string s){
37+ vs result;
38+ if (s == " " ){
39+ result.push_back (" " );
40+ return result;
41+ }
42+ for (int i=0 ; i<s.length (); ++i){
43+ string c = s.substr (i, 1 );
44+ string t = s;
45+ vs res = permu1 (t.erase (i, 1 ));
46+ for (int j=0 ; j<res.size (); ++j){
47+ result.push_back (c + res[j]);
48+ }
49+ }
50+ return result;
51+ }
52+ int main (){
53+ string s = " abc" ;
54+ vs res = permu1 (s);
55+ for (int i=0 ; i<res.size (); ++i)
56+ cout<<res[i]<<endl;
57+ return 0 ;
58+ }
You can’t perform that action at this time.
0 commit comments