Leetcode31. Next Permutation

本文介绍了一个算法问题——实现下一个排列,该问题要求在给定一组数字序列的情况下找出字典序上比当前序列大的下一个排列。若不存在这样的排列,则将序列重新排列为最小的组合(升序)。文章详细解释了算法步骤,并提供了C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,31,3,2
3,2,11,2,3
1,1,51,5,1


这题完全没看懂, 百度了好多才弄明白基本题意,大概说一下我的理解,从后向前遍历,找到第一个打破递减顺序的数字的坐标。然后找出来已经遍历过的序列里中比这个数字大但还是其中最小的数字。
说的也是云里雾里,这题出的不咋好我觉得。。。哈哈哈
不知道到底要干点啥。。
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        
        int index=nums.size()-1;
        while(nums[index]<=nums[index-1])
        {
            index--;
        }
        if(index==0)
        {
            sort(nums.begin(),nums.end());
            return;
        }
        int min=INT_MAX;
        int mindex=INT_MAX;
        for(int i=index;i<=nums.size()-1;i++)
        {
              if(nums[i]>nums[index-1])
              {
                  if(nums[i]<min)
                  {
                      min=nums[i];
                      mindex=i;
                  }
              }
        }
        int temp=nums[index-1];
        nums[index-1]=nums[mindex];
        nums[mindex]=temp;
        sort(nums.begin()+index,nums.end());
      
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值