Leetcode39组合总和

代码:

class Solution {
    public List> combinationSum(int[] candidates, int target) {
        List> res = new ArrayList<>();
        List curRes = new ArrayList<>();
        Arrays.sort(candidates);
        comb(0,curRes,res,candidates,target);
        return res;
    }
    public void comb(int idx,List curRes,List> res, int[] candidates, int target){
        for(int i=idx;i cr = new ArrayList<>(curRes);
                res.add(cr);
                curRes.remove(curRes.size() - 1);
            }else if(target-candidates[i]>0){
                curRes.add(candidates[i]);
                comb(i,curRes,res,candidates,target-candidates[i]);
                if(curRes.size()>0){
                    curRes.remove(curRes.size() - 1);
                }
            }else{
                if(curRes.size()>0){
                    // curRes.remove(curRes.size() - 1);
                    return;
                }
            }
        }
    }
}

这好像叫回溯法

你可能感兴趣的:(算法)