Leetcode 31. Next Permutation
题目:
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 and use only constant 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
Solution
只有一种解法了。
我们先列出一组字典序的排列,然后找找规律
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
......
有点难以寻找,但是到了最后,我们可以总结出来这样一个规律,可以直接找到下一个字典序。
我们以1 4 3 2
为例子说明。
(1) 首先,先从后往前遍历,找到第一组顺序的组合。在例子中,我们可以找到1 4
。此时我们记录下这队组合中前边那个,也就是1
。
(2) 然后,我们再次从后往前遍历,在这个数字的后边寻找比上一步中找到的那个数字大的最小的数。在这个例子中,我们进行比较,2
比1
大,3
,4
比1
大但是比同样也比2
大,因此,我们取2
作为这一步寻找的结果。
(3) 现在,我们交换2
与1
。得到2 4 3 1
。
(4) 然后,把较前那个数字之后的所有部分进行逆序。即将4 3 1
进行逆序。这样我们就得到了下一个字典序。
代码如下:
void nextPermutation(vector<int>& nums) {
// (1)
int i = -1;
for (i = nums.size() - 1; i > 0; i--) {
if (nums[i-1] < nums[i]) {
break;
}
}
i--;
if (i == -1) {
std::sort(nums.begin(), nums.end());
return;
}
// (2)
int min_greater_i = nums.size() - 1, min_greater = INT_MAX;
for (int j = nums.size() - 1; j > i; j--) {
if (nums[j] > nums[i] && nums[j] < min_greater) {
min_greater_i = j;
min_greater = nums[j];
}
}
// (3)
swap(nums[i], nums[min_greater_i]);
// (4)
reverse(nums.begin() + i + 1, nums.end());
return;
}
代码注释中的(1)、(2)、(3)、(4)
等和解法中的标记相对应。