1. 程式人生 > >Leetcode 39 & 40. Combination Sum I &II

Leetcode 39 & 40. Combination Sum I &II

Combination Sum I

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res=[]
        candidates.sort()
        self.back(candidates,target,res,[])
        return
res def back(self,nums,target,res,tmp): if(sum(tmp)==target): tmp1=tmp.copy() res.append(tmp1) return else: for i in range(len(nums)): if sum(tmp)+nums[i]>target: break else: tmp.
append(nums[i]) self.back(nums[i:],target,res,tmp) tmp.pop()

Combination Sun II(slow)

class Solution:
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
res=[] candidates.sort() self.back(candidates,target,res,[]) return res def back(self,nums,target,res,tmp): if(sum(tmp)==target and not tmp in res): tmp1=tmp.copy() res.append(tmp1) return else: for i in range(len(nums)): if sum(tmp)+nums[i]>target: break else: tmp.append(nums[i]) //I different self.back(nums[i+1:],target,res,tmp) tmp.pop()

Combination Sum II (fast)

class Solution:
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res=[]
        candidates.sort()
        self.back(candidates,target,res,[])
        return res
    def back(self,nums,target,res,tmp):
        if(sum(tmp)==target):
            tmp1=tmp.copy()
            res.append(tmp1)
            return
        else:
            for i in range(len(nums)):
                if sum(tmp)+nums[i]>target:
                    break
                //slow different
                elif not i==0 and nums[i]==nums[i-1]:
                    continue
                else:
                    tmp.append(nums[i])
                    //I different
                    self.back(nums[i+1:],target,res,tmp)
                    tmp.pop()