LeetCode40.组合总和------Java

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
思路:
1.先对数组排序,
2.分为三组情况
①sum==target
加入到组合就行
②sum<target
继续递归调用
③sum>target
停止

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);//先将数组进行排序
        ArrayList<Integer> temp = new ArrayList<Integer>();
        ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
        
        generate(0,candidates,temp,result,0,target);//初始化的成员方法
        return result;
	}
    public void generate(int i,int[] candidates,ArrayList<Integer> temp,ArrayList<List<Integer>> result,int sum,int target){
       
        for(int j = i; j< candidates.length;j++){
            sum+=candidates[j];
            if (sum == target){
                temp.add(candidates[j]);
                result.add(new ArrayList<Integer>(temp));
                temp.remove(temp.size()-1);
                break;
            }
            if(sum < target){
                temp.add(candidates[j]);
                // result.add(new ArrayList<Integer>(temp));
                generate(j+1,candidates,temp,result,sum,target);
                sum-=candidates[j];
                temp.remove(temp.size()-1);
                while( j < candidates.length-1 && candidates[j]==candidates[j+1]){
                    j++;
                }
            }
            if(sum > target){
                break;
            }
        }
        
        
    }
}

如有疑问,请留言联系。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值