c++ 全排列

在C++中,全排列(permutation)可以使用递归算法或标准库函数来实现。以下是使用递归和STL库std::next_permutation来生成一个集合的全排列的两种方法。

方法一:递归算法

递归方法通过交换元素来生成所有可能的排列组合。

#include <iostream>
#include <vector>
#include <algorithm>

void permute(std::vector<int>& nums, int l, int r, std::vector<std::vector<int>>& result) {
    if (l == r) {
        result.push_back(nums);
    } else {
        for (int i = l; i <= r; ++i) {
            std::swap(nums[l], nums[i]);
            permute(nums, l + 1, r, result);
            std::swap(nums[l], nums[i]); // backtrack
        }
    }
}

int main() {
    std::vector<int> nums = {1, 2, 3};
    std::vector<std::vector<int>> result;
    permute(nums, 0, nums.size() - 1, result);

    for (const auto& perm : result) {
        for (int num : perm) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

方法二:使用STL库std::next_permutation

std::next_permutation是C++标准库中提供的函数,用于生成字典序中的下一个排列。可以通过不断调用该函数来生成所有的排列组合。

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> nums = {1, 2, 3};
    std::sort(nums.begin(), nums.end()); // 确保初始状态是最小排列

    do {
        for (int num : nums) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    } while (std::next_permutation(nums.begin(), nums.end()));

    return 0;
}

方法三:使用C++11或更高版本的std::vectorstd::algorithm

如果您使用的是C++11或更高版本,可以结合std::vectorstd::algorithm来简化代码。

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> nums = {1, 2, 3};
    do {
        for (const int& num : nums) {
            std::cout << num << " ";
        }
        std::cout << std::endl;
    } while (std::next_permutation(nums.begin(), nums.end()));

    return 0;
}

这三种方法都能有效地生成并打印一个集合的所有排列。第一种方法通过递归和回溯的方式,适合理解递归思想和回溯算法的实现;第二种和第三种方法利用标准库函数std::next_permutation,简化了代码实现,适合实际项目中的快速应用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心瞳几何原语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值