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 bool comp(const int &a, const int &b)
     2 {
     3     return a > b;
     4 };
     5 
     6 class Solution {
     7 public:
     8     void nextPermutation(vector<int> &num) {
     9         // Start typing your C/C++ solution below
    10         // DO NOT write int main() function
    11         int i;
    12         vector<int>::iterator iter = num.end();
    13         int maxNum = INT_MIN;
    14         for(i = num.size() - 1; i >= 0; i--)
    15         {
    16             iter--;
    17             if (num[i] < maxNum)
    18                 break;
    19             maxNum = max(maxNum, num[i]);                
    20         }
    21                 
    22         if (i >= 0)
    23         {
    24             int k;
    25             int minNum = INT_MAX;
    26             for(int j = i + 1; j < num.size(); j++)
    27                 if (num[j] > num[i] && num[j] < minNum)
    28                 {
    29                     minNum = num[j];
    30                     k = j;
    31                 }
    32             int t = num[i];
    33             num[i] = num[k];
    34             num[k] = t;    
    35             sort(iter + 1, num.end());
    36         }
    37         else
    38             sort(num.begin(), num.end());            
    39     }
    40 };
  • 相关阅读:
    【欧拉质数筛选法 模版】
    【归并排序 逆序对 模版】
    【 lca倍增模板】
    【LSGDOJ 1333】任务安排 dp
    【NOIP2013】火柴排队
    【USACO Feb 2014】Cow Decathlon
    【USACO08NOV】奶牛混合起来Mixed Up Cows
    【LSGDOJ 1351】关灯
    【USACO】干草金字塔
    【USACO】电子游戏 有条件的背包
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787483.html
Copyright © 2011-2022 走看看