40. Combination 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.
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 {
    private List<List<Integer>> ans = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates.length==0||target<=0)
           return null;
        List<Integer> res = new ArrayList<Integer>();
        Arrays.sort(candidates);
        fun(candidates,0,target,res);
        return ans;
          
    }
    private void fun(int[] candidates,int start,int target,List<Integer> curr)
    {
        if(target == 0)
        {  
            List<Integer> list = new ArrayList<Integer>(curr);//若没有这一句,直接用ans.add(curr)的话,curr每次是变化的。
            ans.add(list);
        }
        else
        {
            for(int i = start;i<candidates.length;i++)
            {
                if(i!=start&&candidates[i]==candidates[i-1])  //去除重复
                    continue;
                if(target>=candidates[i])
                {
                    curr.add(candidates[i]);
                    fun(candidates,i+1,target-candidates[i],curr); //下次递归不能从当前位置开始
                    curr.remove(curr.size()-1);
                }
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • SOS 新进外贸业务员的忧虑 应届毕业生 在综合了各方面的条件后选择了目前这一家公司 现在有一点是焦虑的 公司是规...
    雕鸡阅读 1,430评论 0 0
  • 向来仰慕东坡先生,大才!不仅看的通现世更明的懂人心。 食无肉的结果是瘦,居无竹的结果是俗!瘦可以补,俗就无可救药了...
    野花2016阅读 1,722评论 0 0