leetcode记录40.Combination Sum II

40.Combination Sum II

Runtime: 8 ms, faster than 100.00% of C++ online submissions for Combination Sum II.
Memory Usage: 9.8 MB, less than 95.25% of C++ online submissions for Combination Sum II.


class Solution {
public:
    vector> combinationSum2(vector& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        return combination(candidates, target, 0);
    }
    
    vector> combination(vector& candidates, int target, int i) {
        int temp = 0;
        vector> result;
        while (i < candidates.size())
        {
            temp = target - candidates[i];
            if(temp < 0)
            {
                break;
            }

            if (temp == 0)
            {
                vector cb;
                cb.push_back(candidates[i]);
                result.push_back(cb);
                return result;
            }
            else
            {
                vector> result_temp = combination(candidates, temp, i+1);
                for (int j = 0; j < result_temp.size(); j++)
                {
                    result_temp[j].push_back(candidates[i]);
                }
                result.insert(result.end(), result_temp.begin(), result_temp.end());
            }
            
            int val = candidates[i];
            
            while (i < candidates.size() && val == candidates[i])
            {
                i++;
            }
        }
        return result;
    }
    
};

你可能感兴趣的:(leetcode)