H - 排列2
题目链接: H - 排列2
题目概述:Ray又对数字的列产生了兴趣:
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。
Input:每组数据占一行,代表四张卡片上的数字(0<=数字<=9),如果四张卡片都是0,则输入结束。
1 2 3 4
1 1 2 3
0 1 2 3
0 0 0 0
Output:对每组卡片按从小到大的顺序输出所有能由这四张卡片组成的4位数,千位数字相同的在同一行,同一行中每个四位数间用空格分隔。每组输出数据间空一行,最后一组数据后面没有空行。
注意的是每行最后的数字后没有空格。
1234 1243 1324 1342 1423 1432
2134 2143 2314 2341 2413 2431
3124 3142 3214 3241 3412 3421
4123 4132 4213 4231 4312 4321
1123 1132 1213 1231 1312 1321
2113 2131 2311
3112 3121 3211
1023 1032 1203 1230 1302 1320
2013 2031 2103 2130 2301 2310
3012 3021 3102 3120 3201 3210
解题思路:利用stl的 next_permutation 产生下一个排列,然后扔进set 集合中,自动去除重复元素并排序。然后遍历即可。next_permutation是全排列的算法之一,详细的东西百度即可,内容很多。
最终代码:
#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
int main()
{
int a[4], temp = 0;
bool flag = false;
set<int> results;
while (true)
{
for (int i = 0; i<4; i++)
{
cin >> a[i];
}
if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0){
break;
}
if (flag){
cout << endl;
}
flag = true;
do{
temp = a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3];
if (temp>999) results.insert(temp);
} while (next_permutation(a, a + 4));
set<int>::iterator it = results.begin();
for (int i = 1; i<results.size(); i++)
{
cout << *it;
if ((*it) / 1000 == (*(++it)) / 1000){
cout << " ";
}else{
cout << endl;
}
}
cout << *it << endl;
results.clear();
}
return 0;
}