491. 非递减子序列
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void BackTracking(vector<int>& nums, int index){
if(path.size()>=2){
result.push_back(path);
}
unordered_set<int> usedSet;
for (int i=index; i<nums.size(); i++){
if (!path.empty() && nums[i]<path.back() || usedSet.find(nums[i])!=usedSet.end())
continue;
usedSet.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;
}
};
46. 全排列
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 (used[i]==true) continue;
path.push_back(nums[i]);
used[i]=true;
BackTracking(nums, used);
used[i]=false;
path.pop_back();
}
}
vector<vector<int>> permute(vector<int>& nums) {
result.clear();
path.clear();
vector<bool> used(nums.size(), false);
BackTracking(nums, used);
return result;
}
};
组合不强调顺序,排列强调顺序。
47.全排列 II
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void BackTracking(vector<int>& nums, vector<bool>& used){
if (nums.size() == path.size()){
result.push_back(path);
return ;
}
for (int i=0; i<nums.size(); i++){
// used[i - 1] == true,说明同一树枝nums[i - 1]使用过
// used[i - 1] == false,说明同一树层nums[i - 1]使用过
// 如果同一树层nums[i - 1]使用过则直接跳过
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) {
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
BackTracking(nums, used);
return result;
}
};