leetcode 40. Combination Sum II

来源:互联网 发布:软件开发咨询 编辑:程序博客网 时间:2024/05/18 15:04

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

Subscribe to see which companies asked this question.

和上一题差不多,差别在于这里面每个数字只能用一次,但是如果出现多次的数字则可以多次使用,结果不能重复。

因此要对上一题的结果做一些改动,每次递归前判断当前数字和上一个数字是否相同。

public class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        List<List<Integer>> ans = new ArrayList<List<Integer>>();        List<Integer>list = new ArrayList<Integer>();        if(candidates.length==0)return ans;        Arrays.sort(candidates);        helper(candidates,target,0,ans,list);        return ans;    }    public void helper(int[]candidates,int target,int beg,List<List<Integer>> ans,List<Integer>list){        if(target==0){            ans.add(new ArrayList<Integer>(list));            return ;        }        if(target<0||beg>=candidates.length)return ;        for(int j=beg;j<candidates.length;j++){            if(target>=candidates[j]){                if(j>beg&&candidates[j]==candidates[j-1])continue;                list.add(candidates[j]);                helper(candidates,target - candidates[j],j+1,ans,list);                list.remove(list.size()-1);            }            else break;        }    }}