39. 组合总和

39. 组合总和

题目链接:39. 组合总和(中等)

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1
输出: []

示例 4:

输入: candidates = [1], target = 1
输出: [[1]]

示例 5:

输入: candidates = [1], target = 2
输出: [[1,1]]

提示:

  • 1 <= candidates.length <= 30

  • 1 <= candidates[i] <= 200

  • candidate 中的每个元素都 互不相同

  • 1 <= target <= 500

解题思路

该题还是属于“组合”问题,与77. 组合216. 组合总和 III类似。但本题需要注意的是每一个元素是可以重复使用的,并且没有元素个数的限制(不过有元素总和的限制)。另外,可以发现,当元素总和大于目标值时,就没有在继续遍历下去的必要,利用这一点可以对本题进行优化。

C++

class Solution {
public:
    vector<int> path;
    vector<vector<int>> result;
    void backTracking(vector<int> candidates, int target,int start, int& sum) {
        // 元素总和 等于 目标值 时,存入 结果集 并返回
        if (sum == target) {
            result.push_back(path);
            return;
        }
        for (int i = start; i < candidates.size(); i++) {
            path.push_back(candidates[i]);
            sum += candidates[i];
            // 修枝,当 sum 已经大于目标值了,就没有必要继续下去了
            if(sum <= target) backTracking(candidates, target, i, sum); // 关键点:用 i(不是i+1) 可以重复得到当前的数
            path.pop_back();
            sum -= candidates[i];
        }
    }
​
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        path.clear();
        result.clear();
        int sum = 0;
        backTracking(candidates, target, 0, sum);
        return result;
    }
};

JavaScript

let path = [];
let result = [];
​
const backTracking = (candidates, target, start, sum) => {
    if (sum === target) {
        result.push([...path]);
        return;
    }
    for (let i = start; i < candidates.length; i++) {
        path.push(candidates[i]);
        sum += candidates[i];
        if (sum <= target) backTracking(candidates, target, i, sum);
        path.pop();
        sum -= candidates[i];
    }
}
​
var combinationSum = function(candidates, target) {
    path = [];
    result = [];
​
    backTracking(candidates, target, 0, 0);
    return result;
};

 

posted @ 2021-12-23 14:33  wltree  阅读(59)  评论(0编辑  收藏  举报