39. Combination Sum

来源:互联网 发布:tc编程案例 编辑:程序博客网 时间:2024/05/22 08:21

题目描述:

Given a set of candidate numbers (C(without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.
题目要求给出一个正整数数组,与一个目标整数,求出所有和为目标数的所有组合。我们可以用深度优先的方法搜索。将结果保存在一个向量中。如果结果不符合,则回到上一节点。如果结果符合,则将结果存进另一向量中。代码如下:

class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> results;        sort(candidates.begin(), candidates.end());        helper(results,vector<int>{},candidates,target,0);        return results;    }    void helper(vector<vector<int>> &results, vector<int> result, vector<int>& c, int target, int index){        if(target == 0){            results.push_back(result);            return;        }        for(int i = index; i < c.size() && target >= c[i]; ++i){            result.push_back(c[i]);            helper(results, result, c, target - c[i], i);            result.pop_back();        }//end of for    }//end of helper};


0 0