Created
March 7, 2021 21:58
-
-
Save mvallebr/b69457da9ac37d457d1f36e9ed2fe8f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from functools import lru_cache | |
| class Solution: | |
| def subset_sum(self, target: int, nums: List[int]): | |
| visited = set() | |
| @lru_cache(None) | |
| def dfs(target_sum): | |
| # print(f"target_sum = {target_sum} nums = {nums}") | |
| if target_sum == 0: | |
| return True | |
| elif target_sum < 0: | |
| return False | |
| else: | |
| for i, num in enumerate(nums): | |
| if i in visited: | |
| continue | |
| visited.add(i) | |
| if dfs(target_sum - num): | |
| return True | |
| visited.remove(i) | |
| return False | |
| return dfs(target) | |
| def canPartition(self, nums: List[int]) -> bool: | |
| nums_sum = sum(nums) | |
| return self.subset_sum(nums_sum // 2, nums) if nums_sum % 2 == 0 else False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment