题目中保证唯一组合小于150个,像这种题目给出限制且数值比较小的,一般都可以使用暴力求解。
dfs遍历其实就相当于暴力,但是递归的方式需要特别设计,每种情况尽量仅访问一次,避免出现冗余的情况。
例如,对于使用for
循环的递归方式,适用于类似全排列,这种结果看重顺序的情况。
在此题中,最终需要的是不重复的数字组合,顺序并不重要,使用for
循环进行递归,会导致大量冗余。
题目明确提出:无重复元素的正整数数组。对于每一个数字都有两种可能: (1) 选 (2) 不选。
可能出现重复的情况:[a,a,b] – [b,a,a]。通过变量index
只增不减加以限制:选择不选的数字将不会再被选择。
附上代码:
class Solution {
vector<vector<int>> out;
public:
void dfs(vector<int>& nums, int target, vector<int>& current, int index) {
if(target == 0) out.push_back(current);
if(target <= 0 || index >= nums.size()) return;
dfs(nums, target, current, index+1);
current.push_back(nums[index]);
dfs(nums, target-nums[index], current, index);
current.pop_back();
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> current;
dfs(candidates, target, current, 0);
return out;
}
};