码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 31. Next Permutation

时间:2017-03-22 22:46:06      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:and   ref   code   color   call   com   sub   hid   tput   

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
 

 

 

思路:对于[a0,a1,...,an]中的ai,如果满足ai>=ai-1>=...>=an,那么序列[ai,ai-1,...,an]就是由构成的序列的ai,ai-1,...,an最大序列,对应的由构成的最小序列就是将最大序列反转的[an,an-1,...,ai]。对于当前序列[a0,a1,...,an],如果存在比之更大的序列,那么新的序列A应该是比当前序列大的序列中最小的。由后向前看:

1.如果an>an-1,那么只要交换an和an-1就可以得到序列A。

2.an-1>=an时,如果an-2比an-1小的话,例如an-1>an-2>=an,只要替换an-2和an-1,就可以得到序列A。

...

可以看到,如果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位是当前情况的最小值,然后剩余元素又组成了剩余元素可以组成的最小值。

 

代码:

 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 }

 

Leetcode 31. Next Permutation

标签:and   ref   code   color   call   com   sub   hid   tput   

原文地址:http://www.cnblogs.com/Deribs4/p/6600514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!