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

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);
        }
    }
}


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务