[leetcode]下一个排列(Next Permutation)

本文深入解析了下一个排列算法,该算法用于将给定数字序列重新排列成字典序中下一个更大的排列。若不存在更大排列,则将序列重排为最小排列(升序)。文章提供了C++实现示例,包括next_permutation()函数的使用方法,以及如何原地修改序列并仅使用常数空间。

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

下一个排列(Next Permutation)

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须原地修改,只允许使用额外常数空间。

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

原题链接:https://leetcode-cn.com/problems/next-permutation/

题解:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        
        next_permutation(nums.begin(),nums.end());
    }
};

c++自带相关函数next_permutation()求下一个排列以及prev_permutation()求前一个排列

这是一个例子:

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::next_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

Output:

The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3

 详细的语法可以参考这个:http://www.cplusplus.com/reference/algorithm/next_permutation/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值