Next Permutation

来源:互联网 发布:ps淘宝调色 编辑:程序博客网 时间:2024/06/16 12:37

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

Java代码:

public class Test_79 {public static void nextPermutation(int[] num) {int len = num.length;if (0 == len || 1 == len)return;boolean flag = false;for (int i = 2; i <= len; i++) {if (num[len - i] < num[len - i + 1]) {flag = true;//判断不满足逆序int tmp = num[len - i];for (int j = 1; j < i; j++) {//将第一个比tmp大的数交换出来if (num[len - j] > tmp) {num[len - i] = num[len - j];num[len - j] = tmp;break;}}// sortfor (int j = 1; j <= (i - 1) / 2; j++) {//对tmp之后的元素进行排序tmp = num[len - j];num[len - j] = num[len - (i - j)];num[len - (i - j)] = tmp;}return;} else {continue;}}if (false == flag) {Arrays.sort(num);return;}}public static void main(String[] arqs) {int[] test = { 1,3,2 };nextPermutation(test);for (int i = 0; i < test.length; i++) {System.out.println(test[i]);}}}

 

0 0