zoukankan      html  css  js  c++  java
  • leetcode: Next Permutation

    http://oj.leetcode.com/problems/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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    思路

    先自己在纸上比划两下,很容易得出以下结论:

    1. 从前往后遍历,找到最后出现的那个满足A[i] < A[i + 1]的数,如果没有,说明数列已经是倒序的,比如[4, 3, 2, 1],那么他的下一个排列很显然,倒序一把就是[1, 2, 3, 4]。
    2. 找到一个位置index_1满足A[index_1] > A[index_1 + 1]后,从index_1位置开始,找到最小的比A[index_1]大的那个数,其位置为index_2,交换A[index_1]和A[index_2],然后对区间index + 1到尾部进行排序。比如当前排列为[1, 2, 7, 4, 3, 6, 5],找到index_1 = 4 (A[2] = 3),找到index_2 = 6 (A[6] = 5),交换后数组为[1, 2, 7, 4, 5, 6, 3],对区间[5, 6]进行排序,得到下一个排列为[1, 2, 7, 4, 5, 3, 6]。 
     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) {
     4         int size = num.size();
     5         
     6         if (size <= 1) {
     7             return;
     8         }
     9         
    10         int index_1 = -1;
    11         
    12         for (int i = 0; i < (size - 1); ++i) {
    13             if (num[i] < num[i + 1]) {
    14                 index_1 = i;
    15             }
    16         }
    17         
    18         if (-1 == index_1) {
    19             reverse(num.begin(), num.end());
    20         }
    21         else {
    22             int min = INT_MAX, index_2;
    23             
    24             for (int i = index_1 + 1; i < size; ++i) {
    25                 if (num[i] > num[index_1]) {
    26                     if (num[i] < min) {
    27                         min = num[i];
    28                         index_2 = i;
    29                     }
    30                 }
    31             }
    32             
    33             swap(num[index_1], num[index_2]);
    34             sort(num.begin() + index_1 + 1, num.end());
    35         }
    36     }
    37 };
  • 相关阅读:
    jsTree展开根节点 设置用户图标
    Js图片缩放代码 鼠标滚轮放大缩小 图片向右旋转
    MySQL删除重复数据
    200道物理学难题——001 三只蜗牛
    慎用GetOpenFileName
    Windows7隐藏字体
    Windows 位图
    Windows 调色板
    C++模板特化
    使用Visual Studio制作安装包
  • 原文地址:https://www.cnblogs.com/panda_lin/p/next_permutation.html
Copyright © 2011-2022 走看看