-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path698.py
70 lines (53 loc) · 2.05 KB
/
698.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
__________________________________________________________________________________________________
sample 32 ms submission
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
def _canPartitionKSubsets(group_sums):
if len(nums) == 0:
return True
num = nums.pop()
for i in range(k):
if group_sums[i] + num <= target:
group_sums[i] += num
if _canPartitionKSubsets(group_sums):
return True
group_sums[i] -= num
if group_sums[i] == 0:
break
nums.append(num)
return False
target, rem = divmod(sum(nums), k)
if rem:
return False
nums.sort()
if nums[-1] > target:
return False
while nums and nums[-1] == target:
nums.pop()
k -= 1
group_sums = [0] * k
return _canPartitionKSubsets(group_sums)
__________________________________________________________________________________________________
sample 12904 kb submission
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
target, rem = divmod(sum(nums), k)
if rem: return False
def search(groups):
if not nums: return True
v = nums.pop()
for i, group in enumerate(groups):
if group + v <= target:
groups[i] += v
if search(groups): return True
groups[i] -= v
if not group: break
nums.append(v)
return False
nums.sort()
if nums[-1] > target: return False
while nums and nums[-1] == target:
nums.pop()
k -= 1
return search([0] * k)
__________________________________________________________________________________________________