码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode 40]组合数和II Combination Sum II

时间:2018-12-01 00:13:02      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:positive   logs   html   solution   get   type   []   put   url   

【题目】

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

Each number in candidates 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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

【思路】

回溯,关键在去重:sort后nums[i-1]==nums[i] continue。

1、[Leetcode 78]求子集 Subset https://www.cnblogs.com/inku/p/9976049.html

2、[Leetcode 90]求含有重复数的子集 Subset II https://www.cnblogs.com/inku/p/9976099.html

3、讲解在这: [Leetcode 216]求给定和的数集合 Combination Sum III

4、[Leetcode 39]组合数的和Combination Sum

【代码】

有参考39的思路设置全局变量+两种情况合并。

class Solution {
    private static List<List<Integer>> ans ;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        ans = new ArrayList<>();
        fun(new ArrayList<Integer>(),candidates,target,0);
        return ans;
    }
    public void fun(List<Integer> tmp,int[] data, int aim,int flag){
        if(aim<=0){
            if(aim==0){
                ans.add(new ArrayList<>(tmp));
            }
            return;
        }
        for(int i=flag;i<data.length;i++){
            if(i>flag&&data[i-1]==data[i])
                continue;
            tmp.add(data[i]);
            fun(tmp,data,aim-data[i],i+1);
            tmp.remove(tmp.size()-1);
        }
    }
}

 

[Leetcode 40]组合数和II Combination Sum II

标签:positive   logs   html   solution   get   type   []   put   url   

原文地址:https://www.cnblogs.com/inku/p/10046893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!