回溯搞定组合总和

图片说明

看到这道题,第一下想到用回溯模板。
直接上代码:

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<Integer> temp = new ArrayList<>();
        dfs(temp, target, candidates, 0);
        return res;
    }

    public void dfs(ArrayList<Integer> temp, int target, int[] candidates, int start){
        if(target == 0){
            res.add(new ArrayList(temp));
            return;
        }
        for(int i = start; i < candidates.length; i++){
            if(i > start && candidates[i] == candidates[i-1]) continue; //去重
            if(candidates[i] <= target){ //剪枝
                temp.add(candidates[i]);
                dfs(temp, target - candidates[i], candidates, i);    //这里注意 如果每个数字在组合中只能有一个 最后参数应为i+1
                temp.remove(temp.size() - 1);
            }
        }
        return;
    }
}
字节算法题解 文章被收录于专栏

最近在刷字节的题库!! 春招给我冲!!!

全部评论

相关推荐

仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务