Leetcode 39. Combination Sum

来源:互联网 发布:免费网络宣传 编辑:程序博客网 时间:2024/05/19 06:47

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.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[  [7],  [2, 2, 3]]

思路:
1. 列举所有可能的组合,结构上就是用backtracking,不同的是判断条件。

class Solution {public:    void helper(vector<int>& candidates, int target,vector<vector<int>>&res,vector<int> cur,int idx){        if(target==0){            res.push_back(cur);            return;         }        for(int i=idx;i<candidates.size();i++){            if(target<candidates[i]) break;            cur.push_back(candidates[i]);            helper(candidates,target-candidates[i],res,cur,i);            cur.pop_back();        }    }    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        //        sort(candidates.begin(),candidates.end());        vector<vector<int>> res;        //vector<int> cur;        helper(candidates,target,res,{},0);//{}表示vector,""表示string        return res;    }};
0 0
原创粉丝点击