题目:html
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).spring
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.spa
1,2,3
→ 1,3,2
.net
3,2,1
→ 1,2,3
code
1,1,5
→ 1,5,1
htm
解题思想:blog
对于数字序列:排序
先看前面2排的话,能够看出来第二排是比第一排要大的,参考字符串比较大小的问题。那么第2个排列是否是第一个排列的下一个排列呢。很明显不是,第3个排列才是, 那么如何获取到下一个排列呢。步骤比较简单:假设数组大小为 n
Supplement:
“这道题是给定一个数组和一个排列,求下一个排列。算法上其实没有什么特别的地方,主要的问题是常常不是一见到这个题就能立刻理清思路。下面咱们用一个例子来讲明,好比排列是(2,3,6,5,4,1),求下一个排列的基本步骤是这样:
1) 先从后往前找到第一个不是依次增加的数,记录下位置p。好比例子中的3,对应的位置是1;
2) 接下来分两种状况:
(1) 若是上面的数字都是依次增加的,那么说明这是最后一个排列,下一个就是第一个,其实把全部数字反转过来便可(好比(6,5,4,3,2,1)下一个是(1,2,3,4,5,6));
(2) 不然,若是p存在,从p开始日后找,找找找,找到第一个比他bigger的数,而后两个调换位置,好比例子中的4。调换位置后获得(2,4,6,5,3,1)。最后把p以后的全部数字倒序,好比例子中获得(2,4,1,3,5,6), 这个便是要求的下一个排列。
以上方法中,最坏状况须要扫描数组三次,因此时间复杂度是O(3*n)=O(n),空间复杂度是O(1)。代码以下:”
1 public class Solution { 2 //http://blog.csdn.net/linhuanmars/article/details/20434115 3 /* 4 假设数组大小为 n 5 1.从后往前,找到第一个 A[i-1] < A[i]的。也就是第一个排列中的 6那个位置,能够看到A[i]到A[n-1]这些都是单调递减序列。 6 2.从 A[n-1]到A[i]中找到一个比A[i-1]大的值(也就是说在A[n-1]到A[i]的值中找到比A[i-1]大的集合中的最小的一个值) 7 3.交换 这两个值,而且把A[n-1]到A[i+1]排序,从小到大。 8 */ 9 public void nextPermutation(int[] num) { 10 if(num==null || num.length==0) 11 return; 12 int i = num.length-2; 13 while(i>=0 && num[i]>=num[i+1]) 14 i--; 15 16 if(i>=0){ 17 int j=i+1; 18 while(j<num.length && num[j]>num[i]) 19 j++; 20 j--; 21 swap(num,i,j); 22 } 23 reverse(num, i+1,num.length-1); 24 } 25 private void swap(int[] num, int i, int j){ 26 int tmp = num[i]; 27 num[i] = num[j]; 28 num[j] = tmp; 29 } 30 private void reverse(int[] num, int i, int j){ 31 while(i < j) 32 swap(num, i++, j--); 33 }
Reference:
http://www.cnblogs.com/springfor/p/3896245.html
http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html
http://blog.csdn.net/m6830098/article/details/17291259