【LeetCode8】40.组合数目II

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    int[] candidates;
    int len;
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        this.candidates = candidates;
		this.len = candidates.length;
        
		Arrays.sort(this.candidates);
		
		backtrack(new ArrayList<Integer>(), -1, target);  //假设有一个前置节点,从-1开始,不然在主程序得加个for(哑结点作为决策树根节点)
        
        return this.res;
    }
    
    
    public void backtrack(List<Integer> pre, int index, int tar){
        if(tar == 0){
			res.add(pre);
			return;
		}
		if(tar < 0){return;}
		
		for(int i = index+1; i < len; i++){
            
            if(i>index+1 && candidates[i]==candidates[i-1]) continue; 
            
			List<Integer> cur = new ArrayList(pre);
            cur.add(candidates[i]);
			backtrack(cur,i,tar-candidates[i]);
		}
		//return;
    }
}

重点:

  • 为了代码结构优化,引入-1的索引位置(就是在决策树引入显示根节点)(哑结点)
  • 既要确保相同元素不在树的同一层,又要保证相同元素可以出现在下一层,所以回溯算法每次for时遇见相同元素只递归一次,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值