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 };
  • 相关阅读:
    hdu 4597 记忆化搜索
    hdu 4494 最小费用流
    hdu 4598 差分约束
    poj 3621 0/1分数规划求最优比率生成环
    poj 1695 动态规划
    noi 97 积木游戏
    hdu 4705 排列组合
    洛谷P2014 选课
    洛谷P1776 宝物筛选
    洛谷P1782 旅行商的背包
  • 原文地址:https://www.cnblogs.com/amadis/p/6707902.html
Copyright © 2011-2022 走看看