LeetCode·40. Combination Sum II

題目:

40. Combination Sum II

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

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

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [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){
            //跳過同一層的重複數值
            if(i > start && nums[i] == nums[i-1])continue;
            v.push_back(nums[i]);
            help(nums, vec, v, i+1, target-nums[i]);
            v.pop_back();
        }
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int> > vec;
        vector<int> v;
        if(candidates.size() < 1)return vec;
        sort(candidates.begin(), candidates.end());
        help(candidates, vec, v, 0, target);

        return vec;
    }
};

結果:


這裏寫圖片描述

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