12、组合总和II

题目描述:
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]
回溯和递归回头还是要多练习练习
代码

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
//		 List<List<Integer>> result = new ArrayList<>();
		 Set<List<Integer>> result = new HashSet<>();
		 List<Integer> tem = new ArrayList<>();
		 Arrays.sort(candidates);
		 getcombinationSum2(candidates, 0, target, result, tem);
		 List list = new ArrayList(result);
		// Set set = new HashSet(list);
		 return list;
	 }
	public static void getcombinationSum2(int []nums, int index, int target,Set<List<Integer>> result,List<Integer> tem){
		if(target == 0){
			result.add(new ArrayList<>(tem));
		}
        if(target < 0){
			return;
		}
		for (int i = index; i < nums.length; i++) {
			tem.add(nums[i]);
			getcombinationSum2(nums, i + 1, target - nums[i], result, tem);
			tem.remove(tem.size() - 1);
		}
	}
}

排名靠前的代码

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
//		 List<List<Integer>> result = new ArrayList<>();
		 Set<List<Integer>> result = new HashSet<>();
		 List<Integer> tem = new ArrayList<>();
		 Arrays.sort(candidates);
		 getcombinationSum2(candidates, 0, target, result, tem);
		 List list = new ArrayList(result);
		// Set set = new HashSet(list);
		 return list;
	 }
	public static void getcombinationSum2(int []nums, int index, int target,Set<List<Integer>> result,List<Integer> tem){
		if(target == 0){
			result.add(new ArrayList<>(tem));
		}
        if(target < 0){
			return;
		}
		for (int i = index; i < nums.length; i++) {
			tem.add(nums[i]);
			getcombinationSum2(nums, i + 1, target - nums[i], result, tem);
			tem.remove(tem.size() - 1);
		}
	}
	 
	 
	 
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/86371822
今日推荐