1. 程式人生 > >python leetcode 416. Partition Equal Subset Sum

python leetcode 416. Partition Equal Subset Sum

每個數都可以取或不取,用字典儲存已經嘗試過的和

class Solution:
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        sumn=sum(nums)
        if sumn&1==1:return False 
        else: return self.canFind(nums,sumn//2,0,len(nums),{})
    def canFind(self,nums,target,start,end,dict1):
        if target in dict1:
            return dict1[target]
        if target==0:
            return True 
        else:
            dict1[target]=False
            for i in range(start,end):
                if self.canFind(nums,target-nums[i],i+1,end,dict1):
                    return True 
            return dict1[target]