zoukankan      html  css  js  c++  java
  • 【Leetcode】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

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) {
     4         int i, j, k, size = num.size();
     5         if (size < 2) {
     6             return;
     7         }
     8         for (i = size - 2; i >= 0; --i) {
     9             if (num[i] < num[i + 1]) {
    10                 break;
    11             }
    12         }
    13         for (j = size - 1; j > i; --j) {
    14             if (num[j] > num[i]) {
    15                 break;
    16             }
    17         }
    18         swap(num[i], num[j]);
    19         for (k = 0; k < (size - i - 1) / 2; ++k) {
    20             swap(num[k + i + 1], num[size - k - 1]);
    21         }
    22     }
    23 };
    View Code

    仔细分析排列的特征,发现如下方法:

    从后往前扫描。找到第一个“打破递增”的位置,下一个排列中该位置元素将被后面的递增序列中,大于其原始值的最小元素所取代。然后,把后半部分的元素排序(原本已经有序,只需要反转即可)。如图:

    来源:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

  • 相关阅读:
    Direct2D 几何计算和几何变幻
    ORACLE触发器具体解释
    HI3518E用J-link烧写裸板fastboot u-boot流程
    NYOJ
    使用ServletFileUpload实现上传
    再看数据库——(2)视图
    cookie登录功能实现
    耗时输入框
    Android开发 ----------怎样真机调试?
    Windows搭建Eclipse+JDK+SDK的Android --安卓开发入门级
  • 原文地址:https://www.cnblogs.com/dengeven/p/3607427.html
Copyright © 2011-2022 走看看