Refer to上一篇
https://blog.csdn.net/weixin_43476349/article/details/83989562
这类题的共同点都是用backtracking,建立一个helper API然后recursion
- input nums needs sort,为了方便remove duplicates
sort(nums.begin(), nums.end())
helper API有几个共同点:
(跟combinations不一样的是)
需要一个tovisit来标记被访问过的元素
loop每次都是从i = 0开始的,但是combinations loop是从start开始的。
所以:
- input:res,row,tovisit (没有start)
- exit condition:
return都是array size要求,exit condition就是:row.size()== nums.size() - 如果input candidates有重复元素,需要remove duplicates,
while(i+1 < candidates.size() && candidates[i] == candidates[i+1]) i++;
比如permutation II。
- Permutations
Given a collection of distinct integers, return all possible permutations.
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>>res;
vector<int>row;
vector<int>tovisit(nums.size(), 0);
helper(res, row, tovisit, nums);
return res;
}
void helper(vector<vector<int>>&res, vector<int>&row, vector<int>&tovisit, vector<int>& nums)
{
if(row.size() == nums.size())
{
res.push_back(row);
return;
}
for(int i = 0; i < nums.size(); i++)
{
if(tovisit[i] == 0)
{
tovisit[i] = 1;
row.push_back(nums[i]);
helper(res, row, tovisit, nums);
row.pop_back();
tovisit[i] = 0;
}
}
}
};
- Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>>res;
vector<int>row;
vector<int>tovisit(nums.size(), 0);
sort(nums.begin(), nums.end());
helper(res, row, tovisit, nums);
return res;
}
void helper(vector<vector<int>>&res, vector<int>&row, vector<int>tovisit, vector<int>& nums)
{
if(row.size() == nums.size())
{
res.push_back(row);
return;
}
for(int i = 0; i < nums.size(); i++)
{
if(tovisit[i] == 0)
{
tovisit[i] = 1;
row.push_back(nums[i]);
helper(res, row, tovisit, nums);
row.pop_back();
tovisit[i] = 0;
while(i + 1 < nums.size() && nums[i] == nums[i+1]) i++;
}
}
}
};