和39题不同的地方:
1.数组中有重复的数
2.数组中的数只能用一次
import java.util.*; /** * Created by lvhao on 2017/7/3. * Given a collection of candidate numbers (C) and a target number (T), * find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 相对于39题,由于每个数只能用一次,所以每次递归时遍历都是从index+1开始,而且由于数组中有重复的数, 所以 1.先用一个set去装结果,当set中不含有的时候才装进去,最后转化为list。 2.加一个判断:当又回溯回来,本层的数要改变的时候,先判断是不是和前边得数相等,相等就continue 但是怎么判断本次是不是回溯回来的呢:如果i > index,就是。 第二种方法更好 */ public class Q40CombinationSum2 { public static void main(String[] args) { int[] nums = new int[]{10, 1, 2, 7, 6, 1, 5}; System.out.println(combinationSum2(nums,8)); } public static List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<>(); backTracking(result,candidates,new ArrayList<>(),target,0); return new ArrayList<>(result); } public static void backTracking(List<List<Integer>> result,int[] candidates, List<Integer> cur,int left,int index) { if(left == 0) { List<Integer> temp = new ArrayList<>(cur); result.add(temp); return; } for(int i = index;i < candidates.length;i++) { if(i > index && candidates[i] == candidates[i-1]) continue; if (candidates[i] <= left) { cur.add(candidates[i]); backTracking(result,candidates,cur,left-candidates[i],i+1); cur.remove(cur.size()-1); } else break; } } }