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

SOLUTION 1:

1.  From the tail to find the first digital which drop
  example: 12 4321

首先我们找到从尾部到头部第一个下降的digit. 在例子中是:2

2. 把从右到左第一个比dropindex大的元素换过来。

3. 把dropindex右边的的序列反序

4. 如果1步找不到这个index ,则不需要执行第二步。

 public class Solution {
public void nextPermutation(int[] num) {
if (num == null) {
return;
} int len = num.length; // Find the index which drop.
int dropIndex = -1;
for (int i = len - 1; i >= 0; i--) {
if (i != len - 1 && num[i] < num[i + 1]) {
dropIndex = i;
break;
}
} // replace the drop index.
if (dropIndex != -1) {
for (int i = len - 1; i >= 0; i--) {
if (num[i] > num[dropIndex]) {
swap(num, dropIndex, i);
break;
}
}
} // reverse the link.
int l = dropIndex + 1;
int r = len - 1;
while (l < r) {
swap(num, l, r);
l++;
r--;
}
} public void swap(int[] num, int l, int r) {
int tmp = num[l];
num[l] = num[r];
num[r] = tmp;
} }

SOLUTION 2:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/permutation/NextPermutation.java

05-11 16:59