Javascript recursive simple


  • 2
    /**
     * @param {number[]} candidates
     * @param {number} target
     * @return {number[][]}
     */
    var combinationSum = function(candidates, target) {
        candidates.sort(function(a,b){return a-b});
        var result=[];
        helper(candidates,target,[],result,0);
        return result;
    };
    function helper(candidates, target, cur, result, idx) {
        var len = candidates.length, i, n;
        for(i=idx;i<len;i++) {
            n = candidates[i];
            cur.push(n);
            if(n===target) {
                result.push(cur.concat());
            } else if(target>n) {
                helper(candidates, target-n, cur.concat(),result, i);
            }
            cur.pop();
        }
    }
    

  • 0
    L

    It is really a good idea. After seeing your code, I understand a little more than before. Thanks for ur coding~


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.