Next Permutation

来源:互联网 发布:java培训 编辑:程序博客网 时间:2024/06/14 04:20

初阶。

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation
of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending
order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the
right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1


#include <iostream>#include <vector>using namespace std;/*思路:1.从后向前,找到第一个违反升序的元素(下降沿)。2.从后向前,找到第一个比下降沿大的元素,作为交换元素。3.交换两个元素。4.反转下降沿后面所有的元素*/class solution{public:void nextPermutation(vector<int> &num){if(num.size() < 2)return;int i = num.size() - 2;while(i > 0 && num[i] > num[i+1])i--;//如果从后到前是升序,无可选方案。选择从前到后升序排列,reverse即可。if(i == 0){reverse(num.begin(),num.end());return;}//从后往前找,第一个比下降沿num[i]大的数,作为交换数int j = num.size() - 1;while(j > i && num[j] <= num[i])j--;//交换num[i]和num[j]swap(num[i],num[j]);//反转下降沿之后的数字reverse(num.begin()+i+1,num.end());return;}};void main(){solution sol;int a[] = {5,4,7,5,3,2};vector<int> v1(a,a+6);sol.nextPermutation(v1);vector<int>::iterator iter;for(iter=v1.begin();iter!=v1.end();iter++){printf("%d ",*iter);}printf("\n");}



进阶。

The set [1,2,3,⋯,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.

思路:求第K个排列,可以调k-1次的下一个排列。

void getKthPermutation(int n,int k){vector<int> vec;for(int i=1;i<=n;i++){vec.push_back(i);}//求第K个排列,只需计算k-1次下一个排列即可for(int i=0;i<k-1;i++){nextPermutation(vec);}return;}



0 0