class Solution31 { public void nextPermutation(int[] nums) { if (nums == null || nums.length == 0) return; int len = nums.length; // 从后往前找到第一个递增对 int sx = len - 1; for (int i = len - 2; i >= 0; i--) { if (nums[i] < nums[i+1]) { sx = i; break; } } if (sx == len-1) { // 没有找到递增对,说明整个子串是递减的 reverse(nums, 0); } // 在[sx+1, len)区间从后往前找第一个大于nums[sx]的位置 int end = len - 1; for (int i = len - 1; i >= sx+1; i--) { if (nums[i] > nums[sx]) { end = i; break; } } // 交换nums[sx]和nums[end] swap(nums, sx, end); reverse(nums, sx+1); } public void swap(int[] nums, int x, int y) { int temp = nums[x]; nums[x] = nums[y]; nums[y] = temp; } public void reverse(int[] nums, int start) { int l = start; int r = nums.length - 1; while (l < r) { swap(nums, l, r); l++; r--; } } }
简化一下:
class Solution31 { public void nextPermutation(int[] nums) { if (nums == null || nums.length == 0) return; int len = nums.length; int sx = len - 2; while (sx >= 0 && nums[sx] >= nums[sx+1]) sx--; if (sx >= 0) { int end = len-1; while (end >= sx+1 && nums[sx] >= nums[end]) end--; swap(nums, sx, end); } reverse(nums, sx+1); } public void swap(int[] nums, int x, int y) { int temp = nums[x]; nums[x] = nums[y]; nums[y] = temp; } public void reverse(int[] nums, int start) { int l = start; int r = nums.length - 1; while (l < r) { swap(nums, l, r); l++; r--; } } }