问题描述

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.
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]
]

问题分析

39. Combination Sum多了两个条件,一个是里面的元素只能用一次;一个是结果集里组合唯一。将39. Combination Sum略微修改一下即可(跳过重复元素以及到下一层时不包含当前元素)。

代码

Github上LeetCode代码:https://github.com/zgljl2012/leetcode-java

public class Solution {
	    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
	    	List<List<Integer>> result = new ArrayList<>();
	    	Arrays.sort(candidates);
	    	fun(result, new ArrayList<>(), candidates, 0, target);
	    	return result;
	    }
	    
	    private void fun(List<List<Integer>> result, List<Integer> list, int[] candidates, int cur, int target) {
	    	if(target > 0) {
	    		for(int i=cur;i<candidates.length;i++) {
	    			if(i>cur && candidates[i] == candidates[i-1]) {
	    				continue;
	    			}
	    			list.add(candidates[i]);
	    			fun(result, list, candidates, i+1, target-candidates[i]);
	    			list.remove(list.size()-1);
	    		}
	    	} else if(target == 0) {
	    		result.add(new ArrayList<>(list));
	    	}
	    }
	}