• 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 }
  • 相关阅读:
    C语言不定参数
    C和C++中的不定参数
    C/C++ 中头文件相互包含引发的问题
    Makefile经典教程(掌握这些足够)
    C语言中volatile关键字的作用
    C++中字符数组与string的相互转换
    C++中 使用数组作为map容器VAlue值的解决方法
    sql 内连接、外连接、自然连接等各种连接
    网站小图标
    Eclipse:快捷
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5564925.html
Copyright © 2020-2023  润新知