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.

Example: Given candidate set [10,1,6,7,2,1,5] and target 8,

A solution set is:

[

[1,7],

[1,2,5],

[2,6],

[1,1,6]

]

分析:

需要认真读题目,并且分析一下会不会有重复出现的情况,这种题目显然会有前后相等的两个数,避免重复,别忘记引入isUsed。

解法:

class Solution {
public:
    /**
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    int getSum(vector<int> instance) {
        int sum = 0;
        for (int i = 0; i < instance.size(); i++) {
            sum += instance[i];
        }
        return sum;
    } 

    void dfs(vector<int> num, 
                vector<int> instance, 
                vector<vector<int> >& res, 
                int start, 
                int target,
                vector<bool>& isUsed) {

        if (getSum(instance) > target) {
            return;
        }

        if (getSum(instance) == target) {
            res.push_back(instance);
            return;
        }

        for (int i = start; i < num.size(); i++) {

            if (i != start && num[i] == num[i - 1] && isUsed[i - 1] == false) {
                continue;
            }

            instance.push_back(num[i]);
            isUsed[i] = true;
            dfs(num, instance, res, i + 1, target, isUsed);
            isUsed[i] = false;
            instance.pop_back();
        }
    }

    vector<vector<int> > combinationSum2(vector<int> &num, int target) {
        // write your code here
        if (num.size() == 0) {
            return vector<vector<int> >();
        }

        sort(num.begin(), num.end() );

        vector<vector<int> > res;
        vector<int> instance;
        vector<bool> isUsed(num.size(), false);
        dfs(num, instance, res, 0, target, isUsed);
        return res;
    }
};

results matching ""

    No results matching ""