LeetCode-Combination Sum II

这种题我总会忘记的细节1。array要先sort  2.循环里面next 要++

这个题有个trick就是原来的array里面有重复的数字 这样可能出现重复的答案 

有两个解决方案 第一个用一个hashset来存那些list 最后把set全都add到最终list里面

还有就是在每个数被加入之前 多一个判断 我差了一点点没写对 就是在循环里面 刚刚进去循环的那个数字即使和前面数字相同也继续做 不要忽略,但是假如不是刚刚进入循环 并且和前一个数一样 就要忽略

    for (int i = cur; i < cand.length; i++){
        if (i > cur && cand[i] == cand[i-1]) continue;


public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        HashSet<List<Integer>> res = new HashSet<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort( candidates );
        helper ( res, list, target, candidates, 0);
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        ans.addAll(res);
        return ans;
    }
    public void helper ( HashSet<List<Integer>> res, List<Integer> list, int target, int [] candidates, int next ){
        if ( target == 0 ){
            res.add( new ArrayList (list));
            return;
        }
        while ( next < candidates.length && candidates[ next ] <= target ){
            list.add ( candidates[ next ] );
            helper ( res, list, target - candidates[next], candidates, next + 1);
            list.remove( list.size() - 1 );
            next ++;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值