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 };
  • 相关阅读:
    Handler详细说明系列(六)——View的post()详解
    2013年6月17日星期一
    2013年6月16日星期日
    线程管理四种方法
    java 线程 ProducerAndConsumer
    POJ 2948 DP
    Java的递归算法
    开机黑屏 仅仅显示鼠标 电脑黑屏 仅仅有鼠标 移动 [已成功解决]
    网络安全审查制度即将推出 手机App安全加密成必定趋势
    递归算法浅谈
  • 原文地址:https://www.cnblogs.com/panda_lin/p/next_permutation.html
Copyright © 2011-2022 走看看