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

  • 相关阅读:
    hibernate关联映射
    线程实现输出结果为100对(1,0)
    hibernate入门
    数据库面试sql
    [网络流24题] 方格取数问题
    [网络流24题] 飞行员配对方案问题
    [CTSC2014]企鹅QQ hash
    [JSOI2010]缓存交换 贪心 & 堆
    Linux相关——画图软件安装
    [NOIP2010] 引水入城 贪心 + 记忆化搜索
  • 原文地址:https://www.cnblogs.com/dengeven/p/3607427.html
Copyright © 2011-2022 走看看