凌云的博客

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

LeetCode 算法题 38. Count and Say

分类:algorithm| 发布时间:2016-09-30 15:27:00


题目

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7,

A solution set is:

[
    [7],
    [2, 2, 3]
]

题意

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

解法

class Solution {
public:
    vector<vector<int>> combinationSum(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) {
            part_.push_back(candidates[i]);
            dfs(candidates, i, target - candidates[i]);
            part_.pop_back();
        }
    }

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