[LeetCode40]Combinations 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]

Analysis:

The idea is similar with the former one, the difference is to get avoid of duplicate numbers.

Java

public class Solution {
    List> result;
	List solu;
	public List> combinationSum2(int[] num, int target) {
		result = new ArrayList<>();
        solu = new ArrayList<>();
        Arrays.sort(num);
        getComboSum(num, target, 0, 0);
        return result;
    }
	public void getComboSum(int []num, int target, int sum, int level){
		if(sum==target){
			result.add(new ArrayList<>(solu));
			return;
		}
		if(sum>target) return;
		for(int i=level;i

update: no global variable

public List> combinationSum2(int[] candidates, int target) {
        List> res = new ArrayList<>();
        List temp = new ArrayList<>();
        Arrays.sort(candidates);
        findSum(candidates, target, 0,0,temp, res);   
        return res;
    }
    public void findSum(int[] candidates, int target, int sum, int level,List temp, List> res){
        if(sum == target) {
            res.add(new ArrayList<>(temp));
            return;
        } else if(sum > target) {
            return;
        } else {
            for(int i=level;i


c++

class Solution {
public:
    void getCombineSum2(
                   int &sum,
                   int level,
                   int target,
                   vector &solution,
                   vector &num,
                   vector> &result
                   ){
    if(sum > target) return;
    if(sum == target) {
        result.push_back(solution);
        return;
    }
    for(int i=level; i > combinationSum2(vector &num, int target) {
    vector solution;
    vector> result;
    int sum = 0;
    sort(num.begin(), num.end());
    getCombineSum2(sum,0,target,solution,num,result);
    return result;
}
};





你可能感兴趣的:(Leetcode,LeetCode,Questions)