LeetCode 46. Permutations 全排列,树形状态回溯

这是一篇关于LeetCode第46题的博客,详细介绍了如何找到给定数字集合的所有可能排列。通过树形状态回溯的方法,解决了数字冲突问题,实现了全排列的算法。博客内容包括题意解释、解题思路、具体代码展示及需要注意的细节。
摘要由CSDN通过智能技术生成

46. Permutations

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]
]

题意

给定一个不重复的数字集合,返回所有的全排列

思路

这里写图片描述

分析:当使用1,余下只能使用2,3排列,选择2只能选择3,得到一种全排列1,2,3. 此时状态回退,选择3只能选择2,得到一种全排列1,3,2

代码

class Solution {
private:
    vector<vector<int>> res;

    vector<bool> used; //辅助数据结构,used[i]表示nums中第i个元素是否被使用过
    // path中保存了一个有index-1个元素的排列。
    // 向这个排列的末尾添加第index个元素, 获得一个有index个元素的排列
    void findPath(vector<int> &nums,int index,vector<int> &path)
    {
        if(index == nums.size())
        {
            res.push_back(path);
            return;
        }

        //遍历数组找到需要添加的第index个元素
        for(int i=0;i<nums.size();i++)
        {
            //if(nums[i] 是否在path中),不在进行path添加操作
            if(!used[i])
            {
                path.push_back(nums[i]); 
                used[i] = true;
                findPath(nums,index+1,path);    

                //返回的过程中,需要尝试nums的其他元素,必须把当前尝试的元素给退回去
                //在path中将最后的元素T除,回退到上一层,且最后的元素一定是刚刚push进去的nums[i]
                //状态回溯
                path.pop_back();
                used[i] = false;
            }

        }
        return;
    }

public:
    vector<vector<int>> permute(vector<int>& nums) {
        if(nums.size()==0)
        {
            return res;
        }

        vector<int> path;
        used = vector<bool>(nums.size(),false);
        findPath(nums,0,path);

        return res;
    }
};

结果

这里写图片描述

注意

此题因为有数字冲突,所以需要状态回退,当不需要状态回退和17. Letter Combinations of a Phone Number类似。
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值