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
  • 相关阅读:
    中国式关系
    太太万岁
    matlab记录运行时间命令
    matlab读xls数据
    matlab,xls转换为mat文件
    matlab里plot设置线形和颜色
    matlab里plot画多幅图像、设置总标题、legend无边框
    matlab显示图像的横纵坐标
    去掉matlab图片空白边缘
    matlab显示原图和灰度直方图
  • 原文地址:https://www.cnblogs.com/freeneng/p/3192910.html
Copyright © 2011-2022 走看看