LeetCode 39. Combination Sum

来源:互联网 发布:中国未破获奇案 知乎 编辑:程序博客网 时间:2024/05/04 19:11

描述

求和为目标值的组合数

解决

与用DP求一共有多少种组合的题目类似


class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> res;        vector<int> tmp;        int length = candidates.size();        func(candidates, target, res, tmp, length, 0);        return res;    }    void func(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& tmp, int& length, int pos)    {        if (target == 0)        {            res.push_back(tmp);            return ;        }        for (int i = pos; i < length; ++i)        {            if (target >= candidates[i])            {                tmp.push_back(candidates[i]);                func(candidates, target - candidates[i], res, tmp, length, i);                tmp.pop_back();            }        }        return ;    }};
0 0
原创粉丝点击