day25 回溯4
491.遞增子序列
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int> &nums, int index) {
if (path.size() > 1) {
res.push_back(path);
}
vector<int> seen(201, 0);
for (int i = index; i < nums.size(); i ++) {
if ((!path.empty() && nums[i] < path.back()) || seen[nums[i]+100] == 1) {
continue;
}
seen[nums[i]+100] = 1;
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums, 0);
return res;
}
};
46.全排列
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int> &nums) {
if (path.size() == nums.size()) {
res.push_back(path);
return;
}
for (int i = 0; i < nums.size(); i ++) {
if (find(path.begin(), path.end(), nums[i]) == path.end()) {
path.push_back(nums[i]);
backtracking(nums);
path.pop_back();
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
backtracking(nums);
return res;
}
};
47.全排列 II
去重沒(méi)搞好懊亡。「峡看了答案才寫(xiě)出的
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int> &nums, vector<bool> &used) {
if (path.size() == nums.size()) {
res.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) {
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
backtracking(nums, used);
return res;
}
};
332.重新安排行程(可跳過(guò))
51.N皇后(適當(dāng)跳過(guò))
37.解數(shù)獨(dú)(適當(dāng)跳過(guò))
這仨先空著历恐,后面再說(shuō)