LeetCode39. Combination Sum

题意

给一个序列以及一个目标值, 使用序列中的数相加和为目标值, 求一共有多少种组合; 每个数可选取多次

解法

  • 递归 + 回溯 + 剪枝

代码


vector<vector<int>> ans;

void dfs(vector<int> res, int target, vector<int> candidates, int index)
{
    if (index == candidates.size()) return;
    if (target < 0) return;
    if (target == 0) {
        ans.push_back(res);
        return;
    }

    dfs(res, target, candidates, index+1);
    if (target - candidates[index] < 0) return;
    res.push_back(candidates[index]);
    dfs(res, target-candidates[index], candidates, index);
}

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    vector<int> res;
    dfs(res, target, candidates, 0);

    return ans;
}
posted @ 2022-07-11 23:16  Figure_at_a_Window  阅读(25)  评论(0)    收藏  举报