LeetCode 39. Combination Sum
Given a set of candidate numbers (C) (without duplicates) 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:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7
,
A solution set is:
[
[7],
[2, 2, 3]
]
完全背包输出所有路径问题
可以用完全背包求一遍,用vector<int>
来维护所有到达该点的前驱结点。
然后从目标位置,开始往前搜索。注意剪枝一下, 可以去除重复路径。
class Solution
{
void dfs(vector<vector<int>> &vec, int target, int pro, vector<vector<int>> &ans, vector<int> res)
{
for(auto &f : vec[target])
{
if(target - f > pro)
return ;
res.push_back(target - f);
if(f != 0)
dfs(vec, f, target-f, ans, res);
else
ans.push_back(res);
res.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
sort(candidates.begin(), candidates.end());
vector<bool> dp(target+1, false);
dp[0] = true;
vector<vector<int>>vec(target+1);
for(int i = 0; i < candidates.size(); ++ i)
{
for(int j = candidates[i]; j <= target; ++ j)
{
if(dp[j-candidates[i]])
{
dp[j] = true;
vec[j].push_back(j-candidates[i]);
}
}
}
vector<vector<int>>ans;
dfs(vec, target, target, ans, vector<int> {});
return ans;
}
};