给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
“123”
“132”
“213”
“231”
“312”
“321”
给定 n 和 k,返回第 k 个排列。
示例 1:
输入:n = 3, k = 3
输出:“213”
示例 2:
输入:n = 4, k = 9
输出:“2314”
示例 3:
输入:n = 3, k = 1
输出:“123”
class Solution {
public:
string getPermutation(int n, int k)
{
string res = "";
for(int i=1;i<=n;i++)
{
res += char(i+48);
}
int index = 0;
do
{
index++;
if(index==k)
return res;
}while(next_permutation(res.begin(),res.end()));
return res;
}
};
// 作者:bing-jian-4
// 链接:https://leetcode-cn.com/problems/permutation-sequence/solution/dfschao-shi-jian-zhi-xue-bu-hui-zhi-hao-ji-yu-next/
这是一个求一个排序的下一个排列的函数,可以遍历全排列,
要包含头文件
下面是以前的笔记与之完全相反的函数还有prev_permutation
(1) int 类型的next_permutation
int main() { int a[3];
a[0]=1;a[1]=2;a[2]=3;
do {
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
}
while (next_permutation(a,a+3)); //参数3指的是要进行排列的长度
//如果存在a之后的排列,就返回true。如果a是最后一个排列没有后
继,返回
false,每执行一次,a就变成它的后继} 输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
如果改成
while(next_permutation(a,a+2));
则输出:
1 2 3
2 1 3
只对前两个元素进行字典排序 显然,如果改成 while(next_permutation(a,a+1));
则只输出:1 2 3
若排列本来就是最大的了没有后继,则next_permutation
执行后,会对排列进行字典升序排序,相当于循环
int list[3]={3,2,1};
next_permutation(list,list+3); cout<<list[0]<<" “<<list[1]<<” "<<list[2]<<endl; //输出: 1 2 3