C++中全排列算法函数next_permutation的使用方法

首先,先看对next_permutation函数的解释: http://www.cplusplus.com/reference/algorithm/next_permutation/?kw=next_permutation

从中可以看出,全排列的第一个序列为从小到大排好序的序列,最后一个序列为从大到小排好序的序列,所以在使用此函数之前,必须先对原序列使用sort进行排序,不然则不能获得其全部的全排列。

看一道来自蓝桥杯的题:

标题:扑克序列

A A 2 2 3 3 4 4, 一共4对扑克牌。请你把它们排成一行。
要求:两个A中间有1张牌,两个2之间有2张牌,两个3之间有3张牌,两个4之间有4张牌。

请填写出所有符合要求的排列中,字典序最小的那个。

例如:22AA3344 比 A2A23344 字典序小。当然,它们都不是满足要求的答案。


请通过浏览器提交答案。“A”一定不要用小写字母a,也不要用“1”代替。字符间一定不要留空格。

解题思路: 枚举全部全排列,对每排列根据条件进行筛选,最后保存到set即可

 1 #include <iostream>  
 2 #include <string>  
 3 #include <set>
 4 #include <vector>  
 5 #include <algorithm>  
 6 
 7 using namespace std;
 8 
 9 int main() 
10 {
11     set<string> sset;
12     string s = "AA223344";
13     sort(s.begin(), s.end());    //一定要先排序,这样它才能成为全排列的第一个序列
14     do
15     {
16         int a1 = s.find('A');
17         int a2 = s.find('A', a1 + 1);
18         int b1 = s.find('2');
19         int b2 = s.find('2', b1 + 1);
20         int c1 = s.find('3');
21         int c2 = s.find('3', c1 + 1);
22         int d1 = s.find('4');
23         int d2 = s.find('4', d1 + 1);
24         if ((a2 - a1 == 2) && (b2 - b1 == 3) && (c2 - c1 == 4) && (d2 - d1 == 5))
25             sset.insert(s);
26     } while (next_permutation(s.begin(), s.end())); //到逆序(从大到小的顺序)的时候返回false
27 
28 
29     for (set<string>::iterator it = sset.begin(); it != sset.end(); ++it)
30         cout << *it << endl;
31 
32     return 0;
33 }

输出为:

2342A3A4
4A3A2432

所以本题答案为: 2342A3A4

 

猜你喜欢

转载自www.cnblogs.com/FengZeng666/p/10458638.html