zoukankan      html  css  js  c++  java
  • [Leetcode 67] 31 Next Permutation

    Problem:

    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

    Analysis:

    First we need to find the first pair that A_i-1 < A_i, and then find the minimum element that is great than A_i-1 from A_i to A_end

    swap A_i-1 and A_min_max.

    at last, sort all the elements of A_i to A_end.

    Then we can get the answer.

    Code:

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int i, min_max;
     7         for (i=min_max=num.size()-1; i>0; i--) {
     8             if (num[i] > num[min_max])
     9                 min_max = i;
    10             
    11             if (num[i] > num[i-1])
    12                 break;
    13         }
    14         
    15         if (i == 0)
    16             reverse(num.begin(), num.end());
    17         else {
    18             for (int j=i; j<num.size(); j++) {
    19                 if (num[j] > num[i-1] && num[j] <= num[min_max])
    20                     min_max = j;
    21             }
    22             
    23             swap(num[i-1], num[min_max]);
    24             
    25             sort(num.begin()+i, num.end());
    26         }
    27     }
    28     
    29     void swap(int &a, int &b) {
    30         int tmp = a;
    31         a = b;
    32         b = tmp;
    33     }
    34 };
    View Code
  • 相关阅读:
    centos通过yum安装php
    CentOS6 用yum安装mysql详解,简单实用
    启用CentOS6.5 64位安装时自带的MySQL数据库服务器
    Python三方库:Pandas(数据分析)
    Python三方库:Numpy(数组处理)
    Java笔记:反射,注解
    Java笔记:多线程
    Java笔记:IO流
    Java笔记:集合
    Java笔记:数组,异常,泛型
  • 原文地址:https://www.cnblogs.com/freeneng/p/3192910.html
Copyright © 2011-2022 走看看