theshy

博客园 首页 新随笔 联系 订阅 管理

 

public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target: An integer
     * @return: A list of lists of integers
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here
        ArrayList<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(0,0,candidates,res,target,new ArrayList<Integer>());
        return res;
    }

    private void dfs(int lastSum,
                     int depth,int[] candidates,
                     ArrayList<List<Integer>> res,
                     int target,
                     List<Integer> lastList) {
        if(lastSum>target)
            return;
        if(lastSum==target){
            res.add(new ArrayList<>(lastList));
            return;
        }
        for(int i=depth;i<candidates.length;++i){
            if(i!=0&&candidates[i]==candidates[i-1])
                continue;
            lastList.add(candidates[i]);
            dfs(lastSum+candidates[i],i,candidates,res,target,lastList);
            lastList.remove(lastList.size()-1);//从底层回溯到这个位置,说明上一个数据已经利用完了,可以滚蛋了(每层只能选一个数据啊)
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        List<List<Integer>> lists = solution.combinationSum(new int[]{2, 3, 6, 7}, 7);
    }
}

 

posted on 2020-03-17 15:59  tziSher  阅读(114)  评论(0编辑  收藏  举报