LeetCode 491.递增子序列
题目链接:
解题思路:
用哈希集合进行去重,同一树层不能取重复元素。
代码:
cpp
class Solution {
public:
vector<vector<int>>result;
vector<int>path;
void backtracking(vector<int>&nums,int startIndex){
if(path.size()>1){
result.push_back(path);
}
unordered_set<int>uset;
for(int i=startIndex;i<nums.size();i++){
if((!path.empty() && nums[i] < path.back())||uset.count(nums[i])){
continue;
}
uset.insert(nums[i]);
path.push_back(nums[i]);
backtracking(nums,i+1);
path.pop_back();
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums,0);
return result;
}
};
LeetCode 46.全排列
题目链接:
解题思路:
用used布尔数组记录当前元素是否用过,进入迭代时,就能保住当前元素不被用两次。
代码:
cpp
class Solution {
public:
vector<vector<int>>result;
vector<int>path;
void backtracking(vector<int>&nums,vector<bool>used){
if(path.size()==nums.size()){
result.push_back(path);
return;
}
for(int i=0;i<nums.size();i++){
if(used[i]==true) continue;
used[i] = true;
path.push_back(nums[i]);
backtracking(nums,used);
path.pop_back();
used[i] = false;
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<bool>used(nums.size(),false);
backtracking(nums,used);
return result;
}
};
LeetCode 47.全排列Ⅱ
题目链接:
代码:
cpp
class Solution {
public:
vector<int>path;
vector<vector<int>>result;
void backtracking(vector<int>&nums,vector<bool>used){
if (path.size() == nums.size()) {
result.push_back(path);
return;
}
for (int i = 0; i < nums.size(); i++){
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
continue;
}
if (used[i] == false) {
used[i] = true;
path.push_back(nums[i]);
backtracking(nums, used);
path.pop_back();
used[i] = false;
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
result.clear();
path.clear();
sort(nums.begin(), nums.end()); // 排序
vector<bool> used(nums.size(), false);
backtracking(nums, used);
return result;
}
};