leetcode 第40题 组合总和 II

题目

给定一个数组 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]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii

思路

        这个题容易想到用递归+回溯的方法来解答,也容易想到用排序的方式做剪枝。但是去重的部分是稍微有些难点的。

        首先问题可以看做是f(pos, target),pos是当前数组索引,target是要组合成的数字,pos初始为0;在数组遍历过程中,每个数字有两种可能,一种是取用,一种是不用,也就是求f(pos, target) => f(pos + 1, target)  + f(pos+1, target - candidates[pos])。递归+回溯可解。

       排序之后的数组可以及时停止,也就进行了剪枝

       但数组中有重复数字,题目要求答案不能包含重复解。在candidates=[2,2],target=2的情况下,上面是有可能会出现重复解的。

        关于去重的方法,我自己的方法是:数组排序后,相同的数字都会相邻,如果当前数字和其左邻相等,且左邻并未在本次递归过程中取用,那么本次的数字也不需要取用。代码如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    Stack<Integer> stack = new Stack<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);


        dfs(candidates, target, -1, 0);
        return result;
    }

    public void dfs(int[]candidates, int target, int lastIndex, int index) {
        if (target == 0) {
            result.add(new ArrayList<>(stack));
            return;
        }

        while (index > 0 && index < candidates.length && candidates[index] == candidates[index - 1] && lastIndex != index - 1) {
            index++;
        }

        if (index >= candidates.length || target < 0) {
            return;
        }
        
        dfs(candidates, target, lastIndex, index+1);
        stack.push(candidates[index]);
        dfs(candidates, target - candidates[index], index,index + 1);
        stack.pop();

    }
}

        官方解法更加巧妙和通透。把数组里的重复数字进行计数,遍历的时候只是对所有可能的数字遍历,数字之间都是不相等的。但是遍历到每个数字的时候,可以选择不用,也可以选择用1.2.3...k个。这个思路其实和上面的取用、不用是一样的,只是从用0、1个变为用0、1、2...k个而已。

耗时:

    50分钟

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值