凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 40. Combination Sum II

分类:algorithm| 发布时间:2016-09-30 18:03:00


题目

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]
]

题意

给出一个数组(C)以及目标数字(T),求出使用 C 中数字使得其和为 T 的所有组合。

在 C 中的每个数字最多只能使用一次。

解法

解法跟上一道题很像,只需要做细微的修改。

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        dfs(candidates, 0, target);
        return ret_;
    }

private:
    void dfs(vector<int> &candidates, int idx, int target) {
        if (target < 0) return;
        if (target == 0) {
            ret_.push_back(part_);
            return;
        }

        const int size = candidates.size();
        for (int i = idx; i < size; ++i) {
            if (i > idx && candidates[i] == candidates[i - 1]) continue;
            part_.push_back(candidates[i]);
            dfs(candidates, i + 1, target - candidates[i]);
            part_.pop_back();
        }
    }

    vector<int> part_;
    vector<vector<int>> ret_;
};