next-permutation

来源:互联网 发布:视频模糊修复软件 编辑:程序博客网 时间:2024/06/05 06:48
packagecom.ytx.array;
/**
 *  题目 :   next-permutation
 * 
 *  描述:    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
                           
                           
 *@authoryuantian xin
 *
 *     题意就是说按照字典序(升序)生成当前排列的下一个排列,如果输入序列已经是降序排列,说明这个是最后一个排列,直接反序输出即可。
 *  1234->1243->1324->1342->1423->1432->4123->...->4321->1234;
 *
 */
publicclass Next_permutation {
       
       
       publicvoid nextPermutation(int[]num) {
             intlen = num.length;
       //从后往前找到第一个升序位置
             intpos = -1;
             for(inti = len - 1; i > 0; i--) {
                    if(num[i] > num[i-1]) {
                           pos= i - 1;
                           break;
                    }
             }
             
             //如果不存在升序,说明这个序列是最后一个排列,直接逆序这个序列并return。
             if(pos< 0) {
                    reverse(num, 0,len-1);
                    return;
             }
             
             //如果找到了升序位置,那么从后往前找,找到pos之后第一个比num[pos]大的位置,并且交换这两个位置上的数。
             for(inti = len-1;i > pos;i--) {
                    if(num[i] > num[pos]) {
                           inttemp = num[i];
                           num[i] = num[pos];
                           num[pos] = temp;
                           break;
                    }
             }
             //逆序pos位置之后的数字
             reverse(num,pos + 1, len-1);
             
    }  
   
       publicvoid reverse(int[]num,int begin, int end) {
             
             inttemp;
             
             while(begin< end) {
                    temp= num[begin];
                    num[begin] = num[end];
                    num[end] = temp;
                    begin++;
                    end--;
             }
             
       }
       publicstatic void main(String[]args) {
             /*int []num = {1,2,3,6,5,4};*/
             int[] num = {1,2,3,4,6,5};
             newNext_permutation().nextPermutation(num);
             for(inti = 0; i < num.length;i++) {
                    System.out.print(num[i] + " ");
             }
       }
}
原创粉丝点击