39. Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
题目:给定一组数和一个目标数,从数组中找到所有相加和为目标数的所有数的组合,这些组合中可以有重复的数。
思路:使用回溯法,找到返回的边界条件,已经获得结果的判断条件

  /**
   * @param {number[]} candidates
   * @param {number} target
   * @return {number[][]}
   */
var combinationSum = function(candidates, target) {
    var candidates_arr = candidates.sort();
    var res = [];
    var sum = 0;
    var arr = [];
    compute(candidates_arr, sum, arr, 0);
    function compute(candidates_arr, sum, arr, j){
        // 返回的边界条件
        if(sum > target){
            return;
        }
        // JS中需要浅拷贝数组,才能获得最终结果
        if(sum === target){
            var temp = arr.slice();
            res.push(temp);
        }
        // 循环条件
        for(let i=j;i<candidates_arr.length && target>=candidates_arr[i];i++){
            arr.push(candidates_arr[i]);
            compute(candidates_arr, sum+candidates_arr[i], arr, i);
            arr.pop();
        }
    }
    return res;
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容