39. Combination Sum LeetCode

题意:给出n个元素和k,求所有由n个元素加和等于k的集合。n个元素可以重复使用多次。
题解:递归

class Solution {
public:
    void dfs(vector<int>& candidates, int target, vector<int>& pre, vector<vector<int>>& ans,int k,int sum)
    {
        if(sum == target) ans.push_back(pre);
        if(sum >= target) return;
        for(int i = k; i < candidates.size(); i++)
            if(sum + candidates[i] <= target)
            {
                pre.push_back(candidates[i]);
                dfs(candidates,target,pre,ans,i,sum + candidates[i]);
                pre.pop_back();
            }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector<vector<int>> ans;
        ans.clear();
        vector<int> pre;
        pre.clear();
        dfs(candidates,target,pre,ans,0,0);
        return ans;
    }
};

你可能感兴趣的:(leetcode)