LeetCode040——组合总和II

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/combination-sum-ii/description/

题目描述:

知识点:回溯、递归、哈希表

思路:用回溯法寻找所有可能的组合

本题和LeetCode039——组合总和几乎一模一样,区别仅在于LeetCode039——组合总和中candidates中的数字可以无限制重复被选取,而本题中candidates中的每个数字在每个组合中只能使用一次。和每个数字的使用次数相关,让我们很容易联想到用哈希表来解决问题。主要的思路还是回溯法,我将和LeetCode039——组合总和不同的一些注意点写一下。

(1)将candidates转换为一张哈希表hashMap,键为candidates中的元素,键对应的值为键在candidates中出现的次数。

(2)在递归函数中,传递的不再是candidates数组,取而代之的是(1)中所得的哈希表。

(3)如果在遍历哈希表的同时,修改哈希表对应的键或者键值,会报ConcurrentModificationException异常。因此我们每一次递归都需要根据hashMap新建一个类型为HashMap<Integer, Integer>的temp变量。在传递给下一层递归函数以及变量回溯过程我们都使用temp,而在遍历时我们使用hashMap,以避免ConcurrentModificationException异常。

(4)往哈希表中新增值和删除值的过程比较复杂,可以抽取出两个函数简化我们的程序书写过程。

时间复杂度和LeetCode039——组合总和相同,是O(n ^ n)级别的,其中n为candidates数组的长度。但是空间复杂度不再是递归层数,因为我们每一层递归都新建了一个哈希表temp,该哈希表的空间复杂度是O(n),因此总的空间复杂度是O(target * n)。

JAVA代码:

public class Solution {

	private List<List<Integer>> listList;

	public List<List<Integer>> combinationSum2(int[] candidates, int target) {
		listList = new ArrayList<>();
		HashMap<Integer, Integer> hashMap = new HashMap<>();
		for (int i = 0; i < candidates.length; i++) {
			addToMap(hashMap, candidates[i]);
		}
		combinationSum2(hashMap, target, new ArrayList<>(), 0);
		return listList;
	}

	private void combinationSum2(HashMap<Integer, Integer> hashMap, int target, List<Integer> list, int sum) {
		if(sum >= target) {
			if(sum == target) {
				listList.add(new ArrayList<>(list));
			}
			return;
		}
		HashMap<Integer, Integer> temp = new HashMap<>(hashMap);
		if(list.size() == 0) {
			for (Integer key : hashMap.keySet()) {
				list.add(key);
				removeFromMap(temp, key);
				combinationSum2(temp, target, list, sum + key);
				list.remove(list.size() - 1);
				addToMap(temp, key);
			}
		}else {
			for (Integer key : hashMap.keySet()) {
				if(key >= list.get(list.size() - 1)) {
					list.add(key);
					removeFromMap(temp, key);
					combinationSum2(temp, target, list, sum + key);
					list.remove(list.size() - 1);
					addToMap(temp, key);
				}
			}
		}
	}
	
	private void addToMap(HashMap<Integer, Integer> hashMap, int element) {
		if(hashMap.containsKey(element)) {
			hashMap.put(element, hashMap.get(element) + 1);
		}else {
			hashMap.put(element, 1);
		}
	}
	
	private void removeFromMap(HashMap<Integer, Integer> hashMap, int element) {
		hashMap.put(element, hashMap.get(element) - 1);
		if(hashMap.get(element) == 0) {
			hashMap.remove(element);
		}
	}
}

LeetCode解题报告:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值