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[i];i++){
            arr.push(candidates_arr[i]);
            compute(candidates_arr, sum+candidates_arr[i], arr, i);
            arr.pop();
        }
    }
    return res;
};

你可能感兴趣的:(39. Combination Sum)