【LeetCode】46. Permutations

算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

全排列问题:题目让输出给定的n个不同数字的全排列,这里使用递归的方法,每次增加一个元素,将这个元素从候选集中移除,递归的重复上述过程,当序列长度达到n时,递归函数返回。直接看代码:

class Solution {
public:
    // 递归函数:len是目标序列长度,candi是当前的候选集合,tmp是正在生成的序列,res是最终结果
    void fun(const int &len, vector<int> candi, vector<int> tmp, vector<vector<int>> &res) {
        if (tmp.size() == len) res.push_back(tmp); // tmp长度够了,说明已经生成了一个排列,加入到结果集res中
        else {
            for (int i = 0; i < candi.size(); ++i){
                vector<int> tmp_2(tmp); // 保存当前序列,复制一个临时序列作为下次递归的参数
                tmp_2.push_back(candi[i]); // 选中一个元素,加入到序列中

                int j = 0;
                vector<int> tmp_candi(candi); // 同上,保存当前的候选集,复制一个新的临时候选集
                for (auto tmp_iter = tmp_candi.begin(); tmp_iter < tmp_candi.end(); ++tmp_iter, ++j){
                    if (j == i) tmp_candi.erase(tmp_iter); // 从临时候选集中移除之前选中的元素
                }
                // 使用之前创建的临时变量进行递归,
                fun(len, tmp_candi, tmp_2, res);
            }
        }
    }

    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> tmp;
        fun(nums.size(), nums, tmp, res);
        return res;
    }
};

笔者认为,这种递归方式最主要的是要保存好当前的状态,代码中tmp_2tmp_candi的使用都是为了保存当前递归的状态。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值