leetcode做题记录0040

leetcode 0040

说明

只是为了记录一下,不求多快,也不深究。

会简要描述思路,代码中不写注释。

如碰到不会做的用了别人代码会在博客中标出。

题目描述

在这里插入图片描述

思路

和前面一题一样,只是数组中的元素不能重复使用,把原来temp的类型从List改成Map就行了,记录一下每个使用的数字的索引,temp里面用过了就不再用了。

跑的结果用时惨不忍睹,应该是还有其他好办法的。

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
		List<List<Integer>> ll = new ArrayList<List<Integer>>();
		getCombination(candidates, target, new HashMap<>(), ll);
		return ll;
	}

	public void getCombination(int[] candidates, int target, Map<Integer, Integer> temp, List<List<Integer>> ll) {
		if (target == 0) {
			List<Integer> toList = new ArrayList<Integer>(temp.values());
			for (List<Integer> l : ll) {
				if (isSameList(toList, l)) {
					return;
				}
			}
			ll.add(toList);
			return;
		} else if (target < 0) {
			return;
		} else {
			for (int a = 0; a < candidates.length; a++) {
				if (temp.containsKey(a)) {
					continue;
				}
				temp.put(a, candidates[a]);
				getCombination(candidates, target - candidates[a], temp, ll);
				temp.remove(a);
			}
			return;
		}
	}

	public boolean isSameList(List<Integer> temp, List<Integer> l) {
		if (temp.size() != l.size()) {
			return false;
		}
		List<Integer> t = new ArrayList<Integer>();
		for (int a : temp) {
			t.add(a);
		}
		Collections.sort(t);
		Collections.sort(l);
		for (int i = 0; i < l.size(); i++) {
			if (t.get(i) != l.get(i)) {
				return false;
			}
		}
		return true;
	}
}
发布了77 篇原创文章 · 获赞 1 · 访问量 2053

猜你喜欢

转载自blog.csdn.net/Paul_1i/article/details/105180752