Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

组合总和 #41

Open
JesseZhao1990 opened this issue Jul 22, 2018 · 0 comments
Open

组合总和 #41

JesseZhao1990 opened this issue Jul 22, 2018 · 0 comments

Comments

@JesseZhao1990
Copy link
Owner

JesseZhao1990 commented Jul 22, 2018

image

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function(candidates, target) {
    
    var res = [];
    function dfs(candidates,target,arr,j){
        if(target<0){
            return;
        }
        if(target===0){
            res.push([...arr]);
            return;
        }
        for(var i=j;i<candidates.length;i++){
            arr.push(candidates[i]);
            dfs(candidates,target-candidates[i],arr,i);
            arr.pop();
        }
    }
    dfs(candidates,target,[],0);
    return res;
    
};

解题思路

递归终止的条件就是target等于零,还有一个问题是如何确保收集的结果不重复,这里需要进行剪枝操作

LeetCode原题地址:https://leetcode-cn.com/problems/combination-sum/description/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant