Leetcode: Combination Sum II

来源:互联网 发布:淘宝买伟哥 编辑:程序博客网 时间:2024/05/01 00:23

Problem:

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

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] 


Solution: 

DFS and recursion

The main difference between II and I is that in II,  in each recursion, each value can only be selected once.


code

public class Solution {    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();    public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {                ArrayList<Integer> list = new ArrayList<Integer>();        if (candidates == null || candidates.length == 0) {            result.add(list);            return result;        }                int length = candidates.length;        Arrays.sort(candidates);        selectCombination(candidates,0,length,list, target);        return result;            }    public void selectCombination(int[] candidates, int k, int length, ArrayList<Integer> list, int target) {                if (target == 0) {            ArrayList<Integer> tmp = new ArrayList<Integer>(list);            result.add(tmp);                    }        if (target < 0 || k == length) return;        for (int i = k; i < length; i++) {            if (i != k && candidates[i] == candidates[i - 1]) continue;            list.add(candidates[i]);            selectCombination(candidates, i + 1, length, list, target - candidates[i]);            list.remove(list.size() - 1);                    }    }    }


0 0
原创粉丝点击