您的位置:首页 > 其它

31、Next Permutation

2015-12-15 22:53 99 查看
题目:

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)在当前序列中,从尾端往前寻找两个相邻升序元素,升序元素对中的前一个标记为partition。

(2)然后再从尾端开始寻找第一个大于partition的元素,并与partition指向的元素交换

(3)将partition后的元素(不包括partition指向的元素)逆序排列。

c++版本:

class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i,k;
for(i=nums.size()-2;i>=0;i--)
{
if(nums[i+1]>nums[i])
{
for(k=nums.size()-1;k>i;k--)
if(nums[k]>nums[i])break;
swap(nums[i],nums[k]);
reverse(nums.begin()+i+1,nums.end());
return;
}
}
reverse(nums.begin(),nums.end());
}
};
python版本:

class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for cur in range(len(nums)-2,-1,-1):
if nums[cur+1]>nums[cur]:
for j in range(len(nums)-1,cur,-1):
if nums[j]>nums[cur]:
nums[cur],nums[j] = nums[j],nums[cur]
break
nums[cur+1:] = nums[cur+1:][::-1]
return
nums.reverse()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: