Skip to content

Commit fe17112

Browse files
committed
[LeetCode Sync] Runtime - 390 ms (28.03%), Memory - 49.6 MB (5.07%)
1 parent 89f2da0 commit fe17112

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> if it is possible to divide this array into <code>k</code> non-empty subsets whose sums are all equal.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [4,3,2,3,5,2,1], k = 4
8+
<strong>Output:</strong> true
9+
<strong>Explanation:</strong> It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [1,2,3,4], k = 3
16+
<strong>Output:</strong> false
17+
</pre>
18+
19+
<p>&nbsp;</p>
20+
<p><strong>Constraints:</strong></p>
21+
22+
<ul>
23+
<li><code>1 &lt;= k &lt;= nums.length &lt;= 16</code></li>
24+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
25+
<li>The frequency of each element is in the range <code>[1, 4]</code>.</li>
26+
</ul>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
3+
s, mod = divmod(sum(nums), k)
4+
if mod:
5+
return False
6+
7+
nums.sort()
8+
mask = (1 << len(nums)) - 1
9+
10+
@cache
11+
def dfs(state, temp):
12+
if state == mask:
13+
return True
14+
for i, num in enumerate(nums):
15+
if (state >> i) & 1:
16+
continue
17+
if temp + num > s:
18+
break
19+
if dfs(state | 1 << i, (temp + num) % s):
20+
return True
21+
return False
22+
23+
return dfs(0, 0)

0 commit comments

Comments
 (0)