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
  • 相关阅读:
    根据IP获取省市 .
    支付宝接口使用步骤及总结
    最新调用优酷视频 免前置广告的方法
    SQL新增数据取表主键最新值
    JS获取地址栏参数
    图片(img标签)的onerror事件
    prototype.js的Ajax对IE8兼容问题解决方案
    基于.net技术的 Rss 订阅开发
    JS获取Dropdownlist选中值
    阿里云tomcat启动慢
  • 原文地址:https://www.cnblogs.com/freeneng/p/3192910.html
Copyright © 2011-2022 走看看