zoukankan      html  css  js  c++  java
  • 31. 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,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

     

     

    next_permutation的算法步骤(二找,一交换,一翻转):
    (1)    找到排列中最右边一个升序的首位位置i,x=nums[i]
    (2)    找到排列中第i位右边最后一个比x大的位置j,y=nums[j]
    (3)    交换x,y
    (4)    把第i+1位到最后的部分进行翻转
    1. class Solution {
      private:
          void reverse(vector<int>& nums,int from,int to){
              while(from<to){
                  int temp=nums[from];
                  nums[from++]=nums[to];
                  nums[to--]=temp;
              }
          }
      public:
          void nextPermutation(vector<int>& nums) {
              int size=nums.size();
              int i=size-2;
              while(i>-1&&nums[i]>=nums[i+1])
                  i--;
              if(i<0){
                  reverse(nums,0,size-1);
                  return;
              }
              int k=size-1;
              while(k>i&&nums[k]<=nums[i])
                  k--;
              swap(nums[i],nums[k]);
              reverse(nums,i+1,size-1);
          }
      };



  • 相关阅读:
    LightOJ 1139 8 puzzle + hdu 1043 Eight A*
    hdu 1180 优先队列 + bfs
    hdu 1270
    HDU Doing Homework
    hdu 1171 Big Event in HDU
    hdu 3613 (KMP)回文串
    POJ 3461 Oulipo(KMP)
    POJ 1565(DP状态压缩)
    NYOJ 634 万里挑一(优先队列)
    职场手记1_你想成文什么样的人
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5119824.html
Copyright © 2011-2022 走看看