Leetcode 31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.ide

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).spa

The replacement must be in-place, do not allocate extra memory.code

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.blog

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
 

 

 

思路:對於[a0,a1,...,an]中的ai,若是知足ai>=ai-1>=...>=an,那麼序列[ai,ai-1,...,an]就是由構成的序列的ai,ai-1,...,an最大序列,對應的由構成的最小序列就是將最大序列反轉的[an,an-1,...,ai]。對於當前序列[a0,a1,...,an],若是存在比之更大的序列,那麼新的序列A應該是比當前序列大的序列中最小的。由後向前看:leetcode

1.若是an>an-1,那麼只要交換an和an-1就能夠獲得序列A。get

2.an-1>=an時,若是an-2比an-1小的話,例如an-1>an-2>=an,只要替換an-2和an-1,就能夠獲得序列A。it

...io

能夠看到,若是ai不知足ai>=ai-1>=...>=an對,只要在ai-1,...,an中找到大於ai的最小值ak,交換ai和ak,而後將ai-1,...,ai,...,an反轉,就能夠獲得序列A。首先a1,...,ai+1不變,將ai和ak交換後,仍然知足ai-1>=...>=ai>=...>=an,將[ai-1,ai,..,an]反轉,就能夠獲得離[ai,...,ak,...,an]最近的大於的序列[ak,an-1,...,ai,...,ai-1],這樣就控制了變換後第i位是當前狀況的最小值,而後剩餘元素又組成了剩餘元素能夠組成的最小值。class

 

代碼:im

 1 public class Solution {
 2     public void nextPermutation(int[] nums) {
 3         int i, j;
 4         for (i = nums.length - 2; i >= 0 && nums[i] >= nums[i+1]; --i);
 5         if (i >= 0) {
 6             for (j = i + 1; j < nums.length && nums[i] < nums[j]; ++j);
 7             swap(nums, i, j - 1);
 8         }
 9         i++;
10         j = nums.length - 1;
11         while (i < j) {
12             swap(nums, i++ ,j--);
13         }
14     }
15     public void swap(int[] nums, int i, int j) {
16         nums[i] += nums[j];
17         nums[j] = nums[i] - nums[j];
18         nums[i] -= nums[j];
19     }
20 }
相關文章
相關標籤/搜索