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 };
  • 相关阅读:
    同余方程(codevs 1200)
    Number Sequence(poj 1019)
    Paths on a Grid(poj 1942)
    取余运算(codevs 1497)
    火车站(codevs 2287)
    教官的游戏(codevs 2793)
    转圈游戏(codevs 3285)
    Code(poj 1850)
    菜菜买气球(codevs 2851)
    3Sum
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787483.html
Copyright © 2011-2022 走看看