[Leetcode] Combination Sum

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Combination Sum相关的知识,希望对你有一定的参考价值。

Combination Sum 题解

题目来源:https://leetcode.com/problems/combination-sum/description/


Description

Given a set of candidate numbers (C) (without duplicates) 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.

Example

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

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

Solution

class Solution {
private:
    void backTrack(vector<int>& path, vector<vector<int> >& res,
                   vector<int>& candidates, int begin, int target) {
        if (target == 0) {
            res.push_back(path);
        } else {
            int size = candidates.size();
            if (begin >= size)
                return;
            for (int i = begin; i < size; i++) {
                if (candidates[i] <= target) {
                    path.push_back(candidates[i]);
                    backTrack(path, res, candidates, i, target - candidates[i]);
                    path.pop_back();
                }
            }
        }
    }
public:
    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
        vector<vector<int> > res;
        vector<int> path;
        backTrack(path, res, candidates, 0, target);
        return res;
    }
};

解题描述

这道题类似与经典的零钱兑换问题,在给定的数组candidates,找出所有和为target的数字组合,选择的数字可以重复但解法不能重复。上面使用的是递归回溯的办法,类似DFS,不难理解,下面再多给出使用迭代DP的解法:

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
        vector<vector<vector<int> > > dp(target + 1, vector<vector<int> >());
        dp[0].push_back(vector<int>());
        for (auto candidate : candidates) {
            for (int j = candidate; j <= target; j++) {
                if (!dp[j - candidate].empty()) {
                    auto paths = dp[j - candidate];
                    for (auto& path : paths)
                        path.push_back(candidate);
                    dp[j].insert(dp[j].end(), paths.begin(), paths.end());
                }
            }
        }
        return dp[target];
    }
};

以上是关于[Leetcode] Combination Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 39. Combination Sum

[Leetcode] Combination Sum

[LeetCode]Combination Sum II

LeetCode OJ 39. Combination Sum

LeetCode OJ 40. Combination Sum II

LeetCode 216. Combination Sum III