LeetCode 40 Combination Sum II

題意:

集合中的每個數字只能使用一次,求出所有數字和爲target的方案。


思路:

如果把集合中的數字計數,問題會變得和 http://blog.csdn.net/houserabbit/article/details/72677176 幾乎一致。

我的方法思路與計數思路幾乎一致,只不過我沒有合併數字,而是枚舉每種數字個數的時候只取排在後面的數字,這樣就保證了方案不重複。


代碼:

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
        n = candidates.size();
        count = new int[n];
        vector<vector<int>> ans;
        sort(candidates.begin(), candidates.end());
        dfs(n - 1, target, ans, candidates);
        return ans;
    }

private:
    int n;
    int *count;

    void dfs(int idx, int target, vector<vector<int>> &ans, vector<int> &candidates) {
        if (candidates[idx] <= target &&
            (idx == n - 1 || candidates[idx] != candidates[idx + 1] || count[idx + 1] == 1)) {
            count[idx] = 1;
            int newtar = target - candidates[idx];
            if (newtar == 0) {
                vector<int> res;
                for (int i = idx; i < n; ++i) {
                    if (count[i] == 1) {
                        res.push_back(candidates[i]);
                    }
                }
                ans.push_back(res);
            } else if (idx > 0) {
                dfs(idx - 1, newtar, ans, candidates);
            }
        }
        count[idx] = 0;
        if (idx > 0) {
            dfs(idx - 1, target, ans, candidates);
        }
    }
};


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