1. 程式人生 > >40.Combination Sum II

40.Combination Sum II

題目:

解答:

借用39題的解法,將while改為if做迴圈,並對第一個遞迴式做去重即可。

程式碼:

class Solution {
public:
    void findCompare(vector<int>& candidates, 
                     vector<vector<int>>& result, 
                     vector<int>& tmp,       
                     int sum,
                     int
index, int index2, int len, int target){ int num = candidates[index]; if(index == len || num > target - sum) return; int tmpindex = index; while(candidates[tmpindex] == candidates[tmpindex+1]) ++tmpindex;
findCompare(candidates, result, tmp, sum, tmpindex + 1, index2, len, target); if(num <= target - sum){ tmp[index2++] = num; sum += num; if(sum == target){ vector<int> vec(tmp.begin(), tmp.begin() + index2); result.
push_back(vec); } findCompare(candidates, result, tmp, sum, index + 1, index2, len, target); } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { int len = candidates.size(); sort(candidates.begin(), candidates.end()); vector<vector<int>> result; vector<int> tmp(1000, 0); findCompare(candidates, result, tmp, 0, 0, 0, len, target); return result; } };