39. 组合总和
题目描述
给定一个 无重复元素 的数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的数字可以无限制重复被选取。
说明:
- 所有数字(包括 target)都是正整数。
- 解集不能包含重复的组合。
示例1:
输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例2:
输入:candidates = [2,3,5], target = 8,
所求解集为:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
提示:
-
1 ≤ c a n d i d a t e s . l e n g t h ≤ 30 1 \le candidates.length \le 30 1≤candidates.length≤30
-
1 ≤ c a n d i d a t e s [ i ] ≤ 200 1 \le candidates[i] \le 200 1≤candidates[i]≤200
-
candidate
中的每个元素都是独一无二的。 -
1 ≤ t a r g e t ≤ 500 1 \le target \le 500 1≤target≤500
题解:
搜索+剪枝。
一般这种凑某个数的题目,有一个常用的剪枝技巧:将数组排序,如果 sum + candidates[pos] > target
,可直接停止后面的递归。
对于此题,递归终止条件是:sum == target
。
代码:
class Solution {
public:
vector<vector<int>> ret;
vector<int> ans;
void dfs( vector<int>& candidates, int p, int now, int target ) {
if ( now == target ) {
ret.push_back( ans );
return;
}
for ( int i = p; i < candidates.size(); ++i ) {
if ( now + candidates[i] <= target ) {
ans.push_back( candidates[i] );
dfs( candidates, i, now + candidates[i], target );
ans.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort( candidates.begin(), candidates.end() );
if ( !candidates.size() || candidates[0] > target ) return {};
dfs( candidates, 0, 0, target );
return ret;
}
};
/*
时间:4ms,击败:98.79%
内存:10.7MB,击败:97.64%
*/