Skip to content

Commit c3276f5

Browse files
committed
698
1 parent c150d9e commit c3276f5

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

DFS/traditionalDFS/698.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,54 @@
1+
## Partition to K Equal Sum Subsets
12

3+
#### Description
4+
5+
[link](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code
16+
17+
> 最坏情况:O(n^2)
18+
19+
```python
20+
class Solution:
21+
def canPartitionKSubsets(self, nums, k):
22+
"""
23+
:type nums: List[int]
24+
:type k: int
25+
:rtype: bool
26+
"""
27+
l, s = len(nums), sum(nums)
28+
29+
if s % k:
30+
return False
31+
32+
self.tar = int(s / k)
33+
self.l = l
34+
35+
visit = [0 for _ in range(l)]
36+
37+
nums.sort(reverse = True)
38+
def dfs(k, index, s, cnt):
39+
if k == 1:
40+
return True
41+
42+
if s == self.tar and cnt > 0:
43+
return dfs(k - 1, 0, 0, 0)
44+
45+
for i in range(index, self.l):
46+
if not visit[i] and nums[i] + s <= self.tar:
47+
visit[i] = 1
48+
if dfs(k, i + 1, s + nums[i], cnt + 1):
49+
return True
50+
visit[i] = 0
51+
return False
52+
53+
return dfs(k, 0, 0, 0)
54+
```

0 commit comments

Comments
 (0)