题目:
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:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- 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]
代码:
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int> > ret; vector<int> tmp; int sum = 0; std::sort(candidates.begin(), candidates.end()); Solution::dfs(ret, tmp, sum, candidates, 0, candidates.size()-1, target); return ret; } static void dfs( vector<vector<int> >& ret, vector<int>& tmp, int &sum, vector<int>& candidates, int begin, int end, int target ) { if ( sum>target ) return; if ( sum==target ) { ret.push_back(tmp); return; } for ( int i=begin; i<=end; ++i ) { if ( sum+candidates[i]<=target ) { sum += candidates[i]; tmp.push_back(candidates[i]); Solution::dfs(ret, tmp, sum, candidates, i, end, target); sum -= candidates[i]; tmp.pop_back(); } } } };
tips:
采用深搜模板:
1. 终止条件sum>target
2. 加入解集条件sum==target
3. 遍历当前层所有分支(如果满足sum+candidates[i]<target,则还可以再往上加candidates[i];注意,这里传入下一层的begin下标为i,因为要求元素可以无限多重复)
4. 由于传入下一层始终满足begin<=end,因此不要在终止条件中加入(begin>end)
时间: 2024-10-01 05:01:54