Skip to content

Commit 89c0836

Browse files
committed
no message
1 parent 75bd00b commit 89c0836

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

problems/partition-to-k-equal-sum-subsets.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,26 @@ def search(subs):
1616
target = sum(nums)/k
1717
nums.sort()
1818
return search([0]*k)
19+
20+
21+
22+
class Solution(object):
23+
def canPartitionKSubsets(self, nums, k):
24+
def dfs(currSum, k, s=0):
25+
if k==0: return True
26+
if currSum==target: return dfs(0, k-1)
27+
28+
for i in xrange(s, N):
29+
num = nums[i]
30+
if not visited[i] and num+currSum<=target:
31+
visited[i] = True
32+
if dfs(currSum+num, k, i+1): return True
33+
visited[i] = False
34+
return False
35+
36+
target, remain = divmod(sum(nums), k)
37+
if remain>0: return False
38+
39+
N = len(nums)
40+
visited = [False]*N
41+
return dfs(target, k)

problems/permutations.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,24 @@ def dfs(path, options):
2727
opt = []
2828
dfs([], nums)
2929
return opt
30+
31+
32+
33+
34+
"""
35+
Time complexity: O(N!). Since in this example our choices is N at the beginning, then N-1, then N-2, then N-3... then 1.
36+
Space complexity: O(N!). The recursion takes N level of recursion.
37+
38+
For each `dfs()` we put the `n` in `remains` to the `path`, if there is no `remains`, add the `path` to the `ans`.
39+
"""
40+
class Solution(object):
41+
def permute(self, nums):
42+
def dfs(remains, path):
43+
if not remains: ans.append(path)
44+
45+
for i, n in enumerate(remains):
46+
dfs(remains[:i]+remains[i+1:], path+[n])
47+
48+
ans = []
49+
dfs(nums, [])
50+
return ans

0 commit comments

Comments
 (0)