您的位置:首页 > 其它

Sicily. 全排序输出

2015-10-10 15:27 435 查看
输入一个数字n,输出从1~n ( 1 < n < 10 )组成的数字的全排列,每个排列占一行,输出按照数值升序排列

比如输入3,则输出是:

123

132

213

231

312

321


递归算法。转自这位大神

#include<iostream>
#include<string>

using namespace std;

void permutation(string pre, string remain) {
if (remain.size() == 1) {
cout << pre << remain << endl;
}
else {
for (int i = 0; i < remain.size(); i++) {
string newPre = pre + remain[i];
string newRemain = remain;
newRemain.erase(i, 1);
permutation(newPre, newRemain);
}
}
}

int main() {
int T,n ;
cin >> T;

while (T--) {
cin >> n;

string start = "";
for (char i = '1'; i < '1' + n; i++) {
start += i;
}

permutation("", start);
}
return 0;
}


用<algorithm>的next_permutation的方法(没什么技术含量):

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

int main() {
int T,n ;
cin >> T;

while (T--) {
cin >> n;

string str = "";
for (char i = '1'; i < '1' + n; i++) {
str += i;
}

do {
cout << str << endl;
} while (next_permutation(str.begin(), str.begin() + n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: