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


    求下一排列,由于递减序列就没有下一排列了,那么从右往左找第一个递减序列(就是从左向右的递增的),找到这两个数之后,从右往左找第一个大于这个数的数,交换这两个数之后,再将原来的递减序列(从右向左递增)reverse之后就得到下一排列了。这题本来没写出来,看了别人的实现,代码如下所示:

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int>& nums) {
     4         int sz = nums.size();
     5         int i;
     6         for(i = sz - 1; i > 0; --i){
     7             if(nums[i] > nums[i - 1])
     8                 break;
     9         }
    10         if(i > 0){
    11             i--;
    12             int j = sz - 1;
    13             while(nums[j] <= nums[i]) j--;
    14             swap(nums[i], nums[j]);
    15             reverse(nums.begin() + i + 1, nums.end());
    16         }else
    17             reverse(nums.begin(), nums.end());
    18     }
    19 };
  • 相关阅读:
    常用模板
    pascal 的字符串操作
    war2 洛谷模拟赛day2 t3 状压
    状压搜索 洛谷T47092 作业
    Milking Order
    洛谷九月月赛T1 思考
    C数列下标 牛客OI赛制测试赛2
    钓鱼 洛谷p1717
    机房人民大团结(DP)
    Spark的Straggler深入学习(2):思考Block和Partition的划分问题——以论文为参考
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4922649.html
Copyright © 2011-2022 走看看