一、题目
二、题解
枚举每个位置所有的可能,当前总和等于target时收集答案,如果直接每个位置都考虑n种选法,那么答案是包含重复的,所以我们只需要选择当前位置后面的元素进行组合
class Solution {
public:
vector<vector<int>> res; // 结果集合
vector<int> path, a; // 路径path, a是全局化candidates
int n, t, sum; // n是candidates的元素个数,t是全局化后的 target, sum用于记录dfs过程中路径上的值
void dfs(int u) {
if (sum > t) return; // 如果当前路径总和已经超过目标值则结束
for (int i = u; i < n; i++){ // 开始枚举当前位置及以后的元素作为当前位置的值
sum += a[i]; // 选择i位置
path.push_back(a[i]);
if (sum == t) res.push_back(path); // 如果等于就收集答案
else dfs(i); // 不等于则dfs下一层
path.pop_back(); // 恢复现场
sum -= a[i];
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
a = candidates;
n = a.size(), t = target; // 全局化
dfs(0);
return res;
}
};