返回

[Leetcode]39. Combination Sum(C++)

题目描述

题目链接:39. Combination Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

例子

例子 1

Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations.

例子 2

Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]

例子 3

Input: candidates = [2], target = 1 Output: []

例子 4

Input: candidates = [1], target = 1 Output: [[1]]

例子 5

Input: candidates = [1], target = 2 Output: [[1,1]]

Constraints

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • All elements of candidates are distinct.
  • 1 <= target <= 500

解题思路

[Leetcode]77. Combinations(C++) 的变种,同样需要用回溯法遍历所有组合,但这道题目允许一个数字选择多次,因此在递归调用的 dfs 函数中不需要改变传入索引。并且由于数组中都为正数,因此循环截止条件可以为当前子数组和大于等于 target。(这里我的处理方式是使用 res 表示当前子数组距 target 还有多远,因此返回条件是 res <= 0),代码如下:

#include <vector>

class Solution {
public:
    std::vector<std::vector<int>> combinationSum(std::vector<int>& candidates, int target) {
        std::vector<int> candidate;
        std::vector<std::vector<int>> result;
        dfs(candidates, 0, target, candidate, result);
        return result;
    }

private:
    void dfs(const std::vector<int>& candidates, int idx, int res, std::vector<int>& candidate, std::vector<std::vector<int>>& result) {
        if (res == 0) {
            result.push_back(candidate);
        } else if (res < 0) {
            return;
        }

        for (int i = idx; i < candidates.size(); ++i) {
            candidate.push_back(candidates[i]);
            dfs(candidates, i, res - candidates[i], candidate, result);
            candidate.pop_back();
        }
    }
};
  • 时间复杂度: O(2^n)
  • 空间复杂度: O(2^n)

GitHub 代码同步地址: 39.CombinationSum.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Built with Hugo
Theme Stack designed by Jimmy