def group(arr):
s1 = []
s2 = arr
_sum = sum(arr)
if _sum & 1:
return None, None
n, memo = len(arr), {0: True}
arr.sort(reverse=True)
def dfs(i, new_sum):
if new_sum not in memo:
memo[new_sum] = False
if new_sum > 0 or new_sum < 0:
for j in range(i, n):
if dfs(j + 1, new_sum - arr[j]):
memo[new_sum] = True
s1.append(arr[j])
s2.remove(arr[j])
break
return memo[new_sum]
k = dfs(0, _sum >> 1) # call recursive func
if not k:
return None, None
return s1, s2
s = [2, 8, 5, 5]
group(s)
The above function combines the usage of DFS with Memoization which I have adopted from https://leetcode.com/problems/partition-equal-subset-sum/discuss/276278/Python-DP-and-(DFS%2BMemo) and has modified it slightly to solve the following challenge:
- Description
S is a set of at least 2 integers in no particular order. The question is whether there is a way to split S into 2 sets (S1 and S2), such that the sum of the integers in S1 equals the sum of the integers in S2. An element in S must always be in either S1 or S2, but cannot be in both. In some cases, there could be multiple solutions to the same S.
- Challenge
Write a function called group that takes in S, and returns either (None, None) (if there is no solution), or a solution (S1, S2). group returns 2 lists. (It is possible for a function in Python to return 2 values - see example here). If there are multiple solutions, only one of them needs to be returned.
- Question
I am having trouble deriving the time complexity of the function as I am not that good with recursion...can anyone please explain/guide me through the process of calculating the above time complexity O(n)?
I really appreciate your help, time and effort. Thank you very much.