zoukankan      html  css  js  c++  java
  • [LeetCode] 31. 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 // refer to http://bangbingsyb.blogspot.com/search?q=Next+Permutation
     2 class Solution {
     3 public:
     4     void nextPermutation(vector<int>& nums) {
     5         int i = 0, j = 0;
     6         
     7         if (nums.size() <= 1) return;
     8         
     9         for (i = nums.size() - 2; i >= 0; i--){
    10             if (nums[i] < nums[i+1]){
    11                 break;
    12             }
    13         }
    14         
    15         if (i < 0) {
    16             sort(nums.begin(), nums.end());
    17             return;
    18         }
    19         
    20         j = i + 1;
    21         while (j < nums.size() && nums[j] > nums[i]) j++;
    22         j--;
    23         
    24         swap(nums[i], nums[j]);
    25         sort(nums.begin() + i + 1, nums.end());
    26         
    27         return;
    28     }
    29 };
  • 相关阅读:
    web--ajax--json
    4.26
    4.25
    4.23
    4.22
    4.20
    4.19
    4.18
    4月问题总结章
    4.17
  • 原文地址:https://www.cnblogs.com/amadis/p/6707902.html
Copyright © 2011-2022 走看看