publicstatic List<List<Integer>> subsets(int[] nums) { //存储结果的list List<List<Integer>> list = new ArrayList<>(); backtrack(list, new ArrayList<>(), nums, 0); return list; }
privatestaticvoidbacktrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){ list.add(new ArrayList<>(tempList)); for (int i = start; i < nums.length; i++) { tempList.add(nums[i]); backtrack(list, tempList, nums, i + 1); tempList.remove(tempList.size() - 1); } }
publicstatic List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> list = new ArrayList<>(); //因为包含重复 先排序 Arrays.sort(nums); backtrack(list, new ArrayList<>(), nums, 0); return list; }
privatestaticvoidbacktrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int start){ list.add(new ArrayList<>(tempList)); for(int i = start; i < nums.length; i++){
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7], [2,2,3] ]
publicstatic List<List<Integer>> combinationSum(int[] nums, int target) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); backtrack(list, new ArrayList<>(), nums, target, 0); return list; }
privatestaticvoidbacktrack(List<List<Integer>> list, List<Integer> tempList, int[] nums, int remain, int start){ if (remain < 0) return; elseif (remain == 0) list.add(new ArrayList<>(tempList)); else { for (int i = start; i < nums.length; i++) { tempList.add(nums[i]); backtrack(list, tempList, nums, remain - nums[i], i); // not i + 1 because we can reuse same elements tempList.remove(tempList.size() - 1); } } }
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Input: candidates = [10,1,2,7,6,1,5], target = 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]