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

LeetCode Next Permutation

时间:2014-11-12 02:02:25      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

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

 

一个数列的全部组合,找出下一个组合。例如123,132,213,231,312,321,123.

从最后一个开始,找出相邻的第一个不是倒序的数,几下索引p,对p之后的元素找出刚刚比p大的,交换后,排序。

 1 public class Solution {
 2     public void nextPermutation(int[] num) {
 3         if (num.length<=1) return ;
 4         int p=0;
 5         int temp=0;
 6         boolean flag=false;
 7         for (int i = num.length-1; i >0 ; i--) {
 8             if (num[i]>num[i-1]){
 9                 p=i-1;
10                 break;
11             }
12         }
13 
14         for (int i = num.length-1; i >=p ; i--) {
15             if (num[i]>num[p]){
16                 flag=true;
17                 temp=num[i];
18                 num[i]=num[p];
19                 num[p]=temp;
20                 break;
21             }
22         }
23         if (p==0&&flag==false)p=-1;
24         Arrays.sort(num,p+1,num.length);
25 
26 
27 
28     }
29 }

 

LeetCode Next Permutation

标签:style   blog   io   color   ar   os   sp   for   div   

原文地址:http://www.cnblogs.com/birdhack/p/4090985.html

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