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
public class Solution { public void nextPermutation(int[] nums) { int len=nums.length,i=len-1,j,tmp; while(i>0 && nums[i]<=nums[i-1])i--; if(i>0){ j=len-1; while(nums[j]<=nums[i-1])j--; tmp=nums[j]; nums[j]=nums[i-1]; nums[i-1]=tmp; } j=len-1; while(i<j){ tmp=nums[i]; nums[i]=nums[j]; nums[j]=tmp; i++;j--; } } }
void nextPermutation(int* nums, int numsSize) { int j,i=numsSize-1,tmp; while(i>0 && nums[i]<=nums[i-1])i--; if(i!=0){ j=numsSize-1; while(j>=i && nums[j]<=nums[i-1])j--; tmp=nums[j]; nums[j]=nums[i-1]; nums[i-1]=tmp; } j=numsSize-1; while(i<j){ tmp=nums[i]; nums[i]=nums[j]; nums[j]=tmp; i++;j--; } }
class Solution { public: void nextPermutation(vector<int>& nums) { int j,len=nums.size(),i=len-1,tmp; while(i>0 && nums[i]<=nums[i-1])i--; if(i>0){ j=len-1; while(j>=i && nums[j]<=nums[i-1])j--; tmp=nums[i-1]; nums[i-1]=nums[j]; nums[j]=tmp; } j=len-1; while(i<j){ tmp=nums[i]; nums[i]=nums[j]; nums[j]=tmp; i++;j--; } } };
class Solution: # @param {integer[]} nums # @return {void} Do not return anything, modify nums in-place instead. def nextPermutation(self, nums): length=len(nums);i=length-1 while i>0 and nums[i]<=nums[i-1]:i-=1 if i>0: j=length-1 while nums[j]<=nums[i-1]:j-=1 tmp=nums[j] nums[j]=nums[i-1] nums[i-1]=tmp j=length-1 while i<j: tmp=nums[i] nums[i]=nums[j] nums[j]=tmp i+=1;j-=1
LeetCode 31 Next Permutation (C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45720473