LeetCode·39. Combination Sum

題目:

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

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

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]
Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

思路:

遞歸

代碼:

class Solution {
public:
    void help(vector<int>& nums, vector<vector<int> > &vec, vector<int> &v, int start, int target){
        if(target < 0)return;
        if(target == 0){
            vec.push_back(v);
            return;
        }

        for(int i = start; i < nums.size(); ++i){
            v.push_back(nums[i]);
            help(nums, vec, v, i, target-nums[i]);
            v.pop_back();
        }
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int> > vec;
        vector<int> v;
        if(candidates.size() < 1)return vec;
        //題中講無重複數字,所以可以不排序
        //如果排序,可以進行提前終止,只處理小於target的數字
        //sort(candidates.begin(), candidates.end());
        help(candidates, vec, v, 0, target);
        return vec;
    }
};

結果:


這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章