题目:
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
解法:
假设有以下排列:
-
首先从后往前看,找到开始变小的那个数,在本例中是2
如果一直是递增的,如 6,5,4,3,2,1说明已经是最后一个数列了,不用进行第二步 -
从后往前找第一个比2大的数,此例中是4,交换他们的位置
-
将第一步找到的位置后的数进行反转,即4后的数进行反转,如果是最后一个排列,则在第一步中的位置是-1,则整个数组进行翻转
C++:
注意两个while语句都带等号,即第一步严格找开始变小的,第二步严格找比第一步大的
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
if(n <= 1) return;
int i = n - 2;
int j = n - 1;
while(i >= 0 && nums[i] >= nums[i + 1]) --i;
if(i >= 0){
while(j >= 0 && nums[j] <= nums[i]) --j;
swap(nums[i] , nums[j]);
}
reverse(nums.begin() + i + 1 , nums.end());
}
};
java:
java中是值传递,所以swap函数不能像c++那么写
Swap in JAVA, 不是想象中的简单
class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
if(nums == null || n <= 1) return;
int i = n - 2;
int j = n - 1;
while(i >= 0 && nums[i] >= nums[i + 1]) --i;
if(i >= 0){
while(j >= 0 && nums[j] <= nums[i]) --j;
swap(nums, i, j);
}
reverse(nums, i + 1 , n - 1);
}
private void reverse(int[] nums, int start, int end){
int i = start;
int j = end;
while(i < j){
swap(nums, i, j);
i++;
j--;
}
}
private void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
python:
python中可以采用元组的方式进行交换
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
if nums == None or n <= 1: return
i = n - 2
j = n - 1
while i >= 0 and nums[i] >= nums[i + 1]: i -= 1
if i >= 0:
while j >= 0 and nums[j] <= nums[i]: j -= 1
nums[i] , nums[j] = nums[j], nums[i]
start = i + 1
end = n - 1
while start < end:
nums[start] , nums[end] = nums[end], nums[start]
start, end = start + 1, end - 1