LeetCode-40. Combination Sum II

一、问题描述
这个题目有点类似于 LeetCode-39.,但是有几点不同:
  1. 数组candidates中可以包含重复元素
  2. 解组合中数组中的元素不能重复出现,一个解组合中,一个元素出现的次数必须小于等于数组中钙元素出现的次数
二、
三、代码
public class Solution {
    List<List<Integer>> result=new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates==null || candidates.length==0)
            return result;
            Arrays.sort(candidates);
        for(int i=0;i<candidates.length;i++){
            if(i!=0 && candidates[i]==candidates[i-1])//i不等于0时,会判断当前元素与前一个元素是否相同
                continue;
            core(candidates,0,i,target,new ArrayList<Integer>());
        }
        return result;
    }
    private int core(int[] candidates,int count,int point,int target,List<Integer> tem){
        count+=candidates[point];
        if(count==target){
            tem.add(candidates[point]);
            result.add(new ArrayList<Integer>(tem));
            tem.remove((Object)candidates[point]);
            return 0;
        }else if(count<target){
            tem.add(candidates[point]);
            for(int i=point+1;i<candidates.length;i++){//i从point+1开始,不再是point
                if(i!=point+1 && candidates[i]==candidates[i-1])//如果i不等于point+1,判断当前元素与前一个元素是否相同。起始判定的元//素只能是point+1,而不能是0,至于为什么,可以自己考虑
                    continue;
                if(core(candidates,count,i,target,tem)>=0)
                    break;
            }
            tem.remove((Object)candidates[point]);
            return -1;
        }else{
            return 1;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值