NextPermutation,寻找下一个全排列

问题描述:给定一个数组是一个全排列,寻找下一个全排列。例如123->132, 321->123, 115->151.

算法分析:从后往前寻找顺序,找到后从往前寻找第一个大于当前元素,即第一个逆序,然后元素交换,重新sort当前元素后面的元素。如果都是逆序,reverse数组。

 1 package Leecode_Permutation;
 2 
 3 import java.util.Arrays;
 4 
 5 public class NextPermutation {
 6     public void nextPermutation(int[] num)  
 7     {  
 8         if(num.length <= 1)  
 9         {
10             return ;  
11         }
12         //从后往前,找正序,下一个是逆序
13         for(int i = num.length - 2; i >= 0; i--)  
14         {  
15             if(num[i] < num[i+1])  
16             {  
17                 int j;  
18                 for(j = num.length - 1; j >= i; j--)  
19                 {
20                     if(num[i] < num[j]) 
21                     {
22                         break;
23                     }
24                 }
25                 // swap the two numbers.  
26                 //num[i] = num[i] ^ num[j];  
27                 //num[j] = num[i] ^ num[j];  
28                 //num[i] = num[i] ^ num[j];  
29                 
30                 int temp = num[i];
31                 num[i] = num[j];
32                 num[j] = temp;
33                 
34                 //sort the rest of arrays after the swap point.  
35                 Arrays.sort(num, i+1, num.length);  
36                 return ;  
37             }  
38         }  
39         //如果都是逆序,说明下一个全排列是正序,reverse it。  
40         for(int i = 0; i < num.length / 2; i++)  
41         {  
42             int tmp = num[i];  
43             num[i] = num[num.length - i - 1];  
44             num[num.length - i - 1] = tmp;  
45         }  
46         return ;  
47         
48     }  
49     public static void main(String[] args) {
50         NextPermutation np = new NextPermutation();
51         int[] num = {1,2};
52         np.nextPermutation(num);
53         for (int i : num) {
54             System.out.println(i);
55         }
56     }
57 }
原文地址:https://www.cnblogs.com/masterlibin/p/5564925.html