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