2017年7月26日 星期三

40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C 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.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
] 
 
39. Combination Sum的衍生 

邏輯大同小異,只是array中的每個元素,只能使用一次。
 
解法如下 

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        
        vector<vector<int>> answerset;
        vector<int> combination;
        sort(candidates.begin(), candidates.end());
        
        combinationSumDFS(candidates, 0, target -0, combination, answerset);
        
        return answerset;
    }
    
    void combinationSumDFS(const vector<int>& candidates, int start, int target, vector<int> &combination, vector<vector<int>>              
                           &answerset)
    {
        // 小於0代表,再找下去也不可能會有符合的數字了
        if (target < 0)
        {
            return;
        }
        // 這個數字組合剛好符合
        else if (target == 0)
        {
            answerset.push_back(combination);
        }
        else
        {
            for (int i = start; i < candidates.size(); i++)
            {
                //排除掉重複的元素
                if (i > start && candidates[i] == candidates[i - 1]) continue;
                
                combination.push_back(candidates[i]);
                //因為已經加入這個元素了,所以要從下一個元素開始
                combinationSumDFS(candidates, i + 1, target - candidates[i], combination, answerset);
                combination.pop_back();
            }
        }        
    }
};

沒有留言 :

張貼留言