回溯法 | 运行重复选择元素组合

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates,target,0, new ArrayList<>());
        return res;
    }
    public void dfs(int[] candidates, int target, int idx, List<Integer> l){
        if(target==0){
            res.add(new ArrayList<>(l));
            return;
        }
        // if(candidates[idx]==target){ error
        //     l.add(candidates[idx]);
        //     res.add(new ArrayList<>(l));
        //     l.remove(l.size()-1);
        //     return;
        // }
        for(int i=idx;i<candidates.length;i++){
            if(target<candidates[i]) continue;
            l.add(candidates[i]);
            dfs(candidates,target-candidates[i],i,l);
            l.remove(l.size()-1);
        }
    }
}


全部评论

相关推荐

09-20 22:39
中南大学
故事和酒66:意思就是用了AI辅助也不一定做得出来,还是有区分度,不然他不会让你用的
点赞 评论 收藏
分享
09-01 10:50
已编辑
东华大学 C++
PDD校招_内推:拼多多意向和开奖一般都比较晚,可能10月11月才出意向
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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