【Leetcode】Combination Sum II

题目链接:https://leetcode.com/problems/combination-sum-ii/

题目:

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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

思路:

candidate set每个元素只允许选择一次。因为set中可能会有重复的元素导致solution set中可能会有重复解,比如sum=8,candidate set[1,1,7],就有两个[1,7]解。每个元素只选择一次,可以在Combination Sum 中改为 dspCombination(sum, i+1);,为了解决重复解的问题,我们引入HashSet保存解,最后在将hashSet转为List返回就好了。

算法:

	int cl[] = null;
	List> iLists = new ArrayList>();
	List list = new ArrayList();
	HashSet> sets = new HashSet>();
	int target = 0;

	public List> combinationSum2(int[] candidates, int target) {
		Arrays.sort(candidates);
		this.cl = candidates;
		this.target = target;
		dspCombination2(0, 0);
		iLists.addAll(sets);  //HashSet 转为 List
		return iLists;
	}

	private void dspCombination2(int sum, int level) {
		if (sum == target) {
			sets.add(new ArrayList(list)); //用HashSet保存解
			return;
		} else if (sum > target) {
			return;
		} else {
			for (int i = level; i < cl.length; i++) {
				sum += cl[i];
				list.add(cl[i]);
				dspCombination2(sum, i + 1); //每个元素只允许选择一次
				list.remove(list.size() - 1);
				sum -= cl[i];
			}
		}
	}



你可能感兴趣的:(leetcode,Leetcode题解java版)