zoukankan      html  css  js  c++  java
  • Next Permutation

    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.

    思路:

    • 首先我们找到从尾部到头部第一个下降的digit. 在例子中是:2
    •  把从右到左第一个比dropindex大的元素换过来。
    •  把dropindex右边的的序列反序
    •  如果1步找不到这个index ,则不需要执行第二步。

    我的代码:

    public class Solution {
        public void nextPermutation(int[] num) {
            if(num==null || num.length<2) return;
            int i = num.length-2;
            int j = num.length-1;
            while(i >= 0)
            {
                if(num[i] < num[i+1]) break;
                i--;
            }
            if(i == -1)
            {
                reverseArray(num, 0, num.length-1);
                return;
            }
            while(j > i)
            {
                if(num[j] > num[i]) break;
                j--;
            }
            int tmp = num[i];
            num[i] = num[j];
            num[j] = tmp;
            reverseArray(num, i+1, num.length-1);
        }
        public void reverseArray(int[] num, int begin, int end)
        {
            while(begin < end)
            {
                int tmp = num[begin];
                num[begin] = num[end];
                num[end] = tmp;
                begin++;
                end--;
            }
        }
    }
    View Code

    学习之处:

    • 主要是如何生成顺序的permutation问题,这个是数学问题,之前学过,但是忘记了,差评
    • 如何reverse一个数组,一个是不断的插入,另外一个方法是交换的方式
    • 改掉自身不好的习惯。
  • 相关阅读:
    第十四周学习报告
    20135206、20135236第四次试验报告
    20135206、20135236第三次试验报告
    第十三周学习报告
    20135206、20135236第二次实验报告
    第十一周学习报告
    20135206于佳心【家庭作业汇总】
    20135236、20135206第一次试验报告
    luogu题解 CF767C 【Garland】
    第七届Code+程序设计全国挑战赛 normal T1 最小路径串
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4460227.html
Copyright © 2011-2022 走看看