一般回溯法可以用两种框架,一种遍历方式(for循环),选择方式(可以理解成到某一节点选择或者不选)。
比较二者的差别:
1.采用遍历方式,for(int i=dep;i
2.遍历方式中for循环的临时变量存储的是temp[i],选择方式中是temp[dep];
3.采用选择方式中,pop完之后还需要继续进行回溯,而for循环中不需要,因为。
一个例子:
Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
class Solution {
public:
vector>res;
vectortemp;
void backtracking(int dep, int sum, vector& candidates)
{
if (sum==0)//子集和为0
{
res.push_back(temp);
return;
}
if (sum < 0) return;
for (int i = dep; i < candidates.size(); i++)
{
temp.push_back(candidates[i]);
backtracking(i, sum - candidates[i], candidates);
temp.pop_back();
}
}
vector> combinationSum(vector& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtracking(0, target, candidates);
return res;
}
};
class Solution {
public:
vector>res;
vectortemp;
void backtracking(vector& candidates, int target,int dep)
{
if (target == 0)
{
res.push_back(temp);
return;
}
if (target < 0) return;
if (dep == candidates.size())return;//若不采用for循环的方式加上dep边界
temp.push_back(candidates[dep]);
backtracking(candidates, target - candidates[dep], dep);
temp.pop_back();
target += candidates[dep];//归位
backtracking(candidates, target - candidates[dep], dep+1);//若不采用for循环的方式记得pop完继续回溯
}
vector> combinationSum(vector& candidates, int target)
{
backtracking(candidates, target, 0);
return res;
}
};
Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note:
For example,
If nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
方法1:
class Solution {
public:
vector>res;
vectortemp;
void backtracking(vector&nums, int pos)
{
res.push_back(temp);
for (int i = pos; i < nums.size(); i++)
{
temp.push_back(nums[i]);
backtracking(nums,i+1);
temp.pop_back();
}
}
vector> subsets(vector& nums)
{
sort(nums.begin(), nums.end());
if (nums.size() == 0) return res;
backtracking(nums, 0);
return res;
}
};
class Solution {
public:
vector>res;
vectortemp;
void backtracking(vector&nums,int dep)
{
if (dep == nums.size())
{
res.push_back(temp);
return;
}
temp.push_back(nums[dep]);
backtracking(nums, dep + 1);
temp.pop_back();
backtracking(nums, dep + 1);
}
vector> subsets(vector& nums)
{
sort(nums.begin(), nums.end());
if (nums.size() == 0) return res;
backtracking(nums, 0);
return res;
}
};