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类似。