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

    Solution: O(n)
    Processes: Take A = {1,3,2} as an example:
    1. Traverse from back to forth, find the turning point, that is A[i] = 3.
    2. Sort from the turning point to the end (A[i] to A[end]), so {3,2} becomes {2,3}.
    3. If i equals to 0, finish! Else, goto 4.
    4. Let j = i, search from A[j] to A[end] to find the first elem which is larger than A[i-1], '2' here.
    5. Swap the elem A[j] with A[i-1].
    Finally, the next permutation is {2,1,3}.

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) {
     4         int i = num.size()-1;
     5         while(i > 0 && num[i] <= num[i-1]) {
     6             i--;
     7         }
     8         sort(num.begin()+i, num.end());
     9         if(i == 0) {
    10             return;
    11         }
    12         int j = i;
    13         while(j < num.size() && num[j] <= num[i-1]) {
    14             j++;
    15         }
    16         swap(num[i-1], num[j]);
    17     }
    18 };
  • 相关阅读:
    Nexus入门指南(图文)[转]
    java注解[转]
    JS设置IE可信站点及ActiveX设置
    ExtJS 4 树
    SQL大全
    基于Spring aop 和JAVA注解方式添加日志
    Excle自动增长序号
    VS 生成后事件
    Oracle命令分解之正则表达式搜索(一)
    Oracle命令分解之……SOUNDEX
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646365.html
Copyright © 2011-2022 走看看