40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.

Each number inCmay only be usedoncein 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 target8,
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

思路:和一差不多

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        Arrays.sort(candidates);
        traceback(list,temp,candidates,0,0,target);
        return list;
    }

    public void traceback(List<List<Integer>> list,List<Integer> temp,int[] arr, int start, int sum, int target){
        if (sum==target){
            list.add(new ArrayList<Integer>(temp));
            return;
        }else if(sum>target){
            return;
        }else{
            for (int i=start;i<arr.length;i++){
                if (i>start&&arr[i]==arr[i-1]) continue;
                temp.add(arr[i]);
                traceback(list,temp,arr,i+1,sum+arr[i],target);
                temp.remove(temp.size()-1);
            }
        }
    }
}

results matching ""

    No results matching ""