LeetCode解题报告--Combination Sum II

题目:

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
题目链接:https://leetcode.com/problems/combination-sum-ii/

分析:题意要求从给定数组找出所有组合的元素值和==target,且元素不可重复使用。该题与Combination Sum的差不多,区别在于元素不可重复使用,可以参考Combination Sum,在Combination Sum的代码基础做些细节的修改,即可。着重解决问题,去重:元素可以重复出现,需要设置判断条件去重,两种方法:
a.在target==0时,添加元素是否重复判断,调用ArrayList的contains()方法,python代码情况会出现超时,java代码可以通过测试;
b.在递归前添加去重判断,如果当前递归出现if i > begin && candidates[i] == candidates[i - 1] continue;, 因为给定数组元素出现重复,如果当前递归符合要求,紧接的递归会再次出现同样的结果,出现重复,故在当前递归直接跳过,只记录紧接的递归结果。如图所示:绿色虚线与橘色实线,在没有跳过第一次递归,直接在进行第二次递归,出现重复的组合。
这里写图片描述

Java代码Accepted:

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {

        List<Integer> subRes = new ArrayList<Integer>();
        List<List<Integer>> result = new ArrayList<List<Integer>>();

        //Special case
        if(candidates.length == 0 || candidates == null)
            return result;

        //Sort array before find combination
        Arrays.sort(candidates);
        //Recursive DFS
        recursionFunction(candidates,0,target,subRes,result);
        return result;
    }

    public static void recursionFunction(int[] candidates,int begin,int target,List<Integer> subRes,List<List<Integer>> result){

        if(target < 0)
            return;
        else if(target == 0){
            //Have to redeclarat subRes as ArrayList<Integer> or can't get resSub
            //Whether duplication
            // if(!result.contains(new ArrayList<Integer>(subRes)))
                result.add(new ArrayList<Integer>(subRes));
            return;
        }else{
            for(int i = begin;i < candidates.length;i ++){
                if(i > begin && candidates[i] == candidates[i - 1])
                    continue;
                subRes.add(candidates[i]);
                recursionFunction(candidates,i + 1,target - candidates[i],subRes,result);
                subRes.remove(subRes.size() - 1);
            }
        }
    }
}

Python Acepted:

class Solution(object):

    def __init__(self):
        self.res = []
        self.subRes = []
        self.target = 0

    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        if(len(candidates) == 0 or candidates == None):
            return self.res

        candidates = sorted(candidates)
        self.recursionFunction(candidates,0,target,self.subRes,self.res)
        return self.res

    def recursionFunction(self,candidates,begin,target,subRes,res):

        if(target < 0):
            return
        elif(target == 0):
            self.res.append(self.subRes)
            return
        else:
            for i in range(begin,len(candidates)):
                if i > begin and candidates[i] == candidates[i - 1]:
                    continue
                self.subRes.append(candidates[i])
                self.recursionFunction(candidates,i + 1,target - candidates[i],self.subRes,self.res)
                self.subRes = self.subRes[:-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值