1.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, 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,4,3,2 -> 2,1,3,4
2,3,1 -> 3,2,1
代码如下:
public class Solution {
public static void nextPermutation(int[] nums){
if(nums == null || nums.length < 2) return;
int pos = nums.length-1,i = pos-1;
while(i >= 0 && nums[i] >= nums[i+1]) i--;
if(i<0) {Arrays.sort(nums); return;}
for(;pos>i;pos--) if(nums[pos]>nums[i]) break;
swap(nums,i,pos);
Arrays.sort(nums,i+1,nums.length);
}
public static void swap(int[] nums,int i,int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
2.
Permutation Sequence
The set [1,2,3,…,n]
contains a total ofn! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"