[牛客网-Leetcode] #数组 中等 next-permutation

下一个全排列 next-permutation

题目描述

实现函数next permutation(下一个排列):将排列中的数字重新排列成字典序中的下一个更大的排列。将排列中的数字重新排列成字典序中的下一个更大的排列。
如果不存在这样的排列,则将其排列为字典序最小的排列(升序排列)
需要使用原地算法来解决这个问题,不能申请额外的内存空间
下面有机组样例,左边是输入的数据,右边是输出的答案
1,2,3→1,3,2
3,2,1→1,2,3
1,1,5→1,5,1

Implement next permutation, which rearranges numbers into the lex
icographically 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

解题思路

  • 思路1:用algorithm头文件下的next_permutation函数,该函数实现将序列重新排列成下一个全排列。
  • 注意要加个if判断,next_permutation函数在已经到达最后一个全排列时会返回false,此时题目要求排列为字典序最小的排列,因此用sort排序
class Solution {
    
    
public:
    void nextPermutation(vector<int> &num) {
    
    
        if(num.size() == 0) return ;
        //如果存在下一个全排列,则返回true,否则返回false
        if(next_permutation(num.begin(), num.end())) {
    
    
            
        } else {
    
    
            sort(num.begin(), num.end());
        }
    }
};
  • 思路2:找到从后往前递增排序最后一个点的下标,swap这个点前一个元素与后面第一个大于此元素的数,然后对后面部分升序排列
    • 例如:1 2 3 7 6 5 1
    • 找到从后往前递增排序最后一个点的下标
    • 如果不存在这样的点,证明整个数组是递减的,已经到达最大的全排列,因此直接对整个数组reverse即可
    • 如果存在这样的点,例如上例中的7,则重新从后往前寻找第一个大于3的数,本例中为5
    • 交换5和3的位置,并对后面部分的数组升序排列,即可得到结果。
class Solution {
    
    
public:
    void nextPermutation(vector<int> &num) {
    
    
        int n = num.size();
        if(n <= 1) return ;
        //标记从后往前递增排序最后一个点的下标
        int index(n - 1);
        //跳出循环说明是num[index] > num[index - 1],即严格递增
        while(index > 0 && num[index] <= num[index - 1]) index --;
        
        if(index == 0) {
    
      //如果不存在这样的点
            reverse(num.begin(), num.end());
        } else {
    
         //如果存在这样的点
            //标记第一个大于这个点前一个元素的数
            int k(n - 1);
            //跳出循环说明是num[k] > num[index - 1],即严格大于
            while(num[k] <= num[index - 1]) k --;
            swap(num[k], num[index - 1]);
            sort(num.begin() + index, num.end());
        }
    }
};

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/106565004
今日推荐