题目:
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
题目的意思是求字典序中的下一个。
输入:1 2 3
它可以生成:1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1.
其中1 3 2是1 2 3 的下一个,所以输出: 1 3 2
输入:3 2 1
它生成的数字跟1 2 3相同,也是:1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1.
其中1 2 3是3 2 1的(循环)下一个,所以输出:1 2 3
思路:
对任意排列:A[0] A[1] A[2] ... A[i]... A[n]
假设 A[i - 1] < A[i],且有A[i] >= A[i+1] >= A[i + 2] >= ... >= A[n - 1]
从A[i]到A[n - 1]中选取一个最小的数A[k],A[k]满足条件:A[k] > A[i - 1]
则A[0] A[1] A[2] ... A[i]... A[n]的下一个排列为
A[0] A[1] A[2] ... A[k] A[n - 1] A[n - 2]... A[k + 1] A[i - 1] A[k - 1] ... A[i]。
例子更能说明:
假设输入为 5 5 2 4 7 6 3
从后往前观察,对于A[5] = 6 >= A[6] = 3。(交换A[5]和A[6]得到的排列: 5 5 2 4 7 3 6 小于原排列,这一步是没有必要做的,只是为了让大家看清楚)
A[4] = 7 >= A[5] >= A[6]。(交换A[4]和A[5]或者A[4]和A[6]等,得到的都比原排列小)
A[3] = 4 < A[4] >= A[5] >= A[6],这时从7 6 3中选择6,6是这三个数中大于4的最小的数,交换A[3]= 4和A[5] = 6,得到: 5 5 2 6 7 4 3
明显5 5 2 6 7 4 3比原排列大,但不是原排列的next permutation。
需要调整7 4 3得到最小的3 4 7,最终就是输出5 5 2 6 3 4 7
对于输入3 2 1
找不到任何一个A[i - 1] < A[i],所以输出为它的(循环)下一个: 1 2 3
代码:
class Solution {
public:
void nextPermutation(vector<int> &num)
{
if(num.size() <= 1)
return;
int index1 = -1,index2;
//从后向前找到开始递减的数的位置,放入index1,比如 5 5 2 4 7 6 3,定位到4,则index1 = 3
for(int i = num.size()-2 ; i >= 0 ; i--)
{
if(i >=0 && num[i] < num[i+1])
{
index1 = i;
break;
}
}
//如果不存在递减的数,即从后向前一直递增,则直接把数字翻转一下即可,比如数组 3 2 1
if(index1 == -1)
{
reverse(num.begin(),num.end());
return;
}
//从后向前找到第一个比num[index1]大的数
for(int j = num.size()-1 ; j > index1 ; j--)
{
if(num[j] > num[index1])
{
index2 = j;
break;
}
}
//交换num[index1]和num[index2]
num[index1] ^= num[index2];
num[index2] ^= num[index1];
num[index1] ^= num[index2];
//对index1后面的数翻转一下即可
reverse(num.begin()+index1+1,num.end());
return;
}
};