1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
partition-to-k-equal-sum-subsets.py 1.70 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 7年前 . add complexity
# Time: O(n*2^n)
# Space: O(2^n)
class Solution(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def dfs(nums, target, used, todo, lookup):
if lookup[used] is None:
targ = (todo-1)%target + 1
lookup[used] = any(dfs(nums, target, used | (1<<i), todo-num, lookup) \
for i, num in enumerate(nums) \
if ((used>>i) & 1) == 0 and num <= targ)
return lookup[used]
total = sum(nums)
if total%k or max(nums) > total//k:
return False
lookup = [None] * (1 << len(nums))
lookup[-1] = True
return dfs(nums, total//k, 0, total, lookup)
# Time: O(k^(n-k) * k!)
# Space: O(n)
# DFS solution with pruning.
class Solution2(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def dfs(nums, target, i, subset_sums):
if i == len(nums):
return True
for k in xrange(len(subset_sums)):
if subset_sums[k]+nums[i] > target:
continue
subset_sums[k] += nums[i]
if dfs(nums, target, i+1, subset_sums):
return True
subset_sums[k] -= nums[i]
if not subset_sums[k]: break
return False
total = sum(nums)
if total%k != 0 or max(nums) > total//k:
return False
nums.sort(reverse=True)
subset_sums = [0] * k
return dfs(nums, total//k, 0, subset_sums)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助