Skip to content

Instantly share code, notes, and snippets.

@dongr0510
Created September 8, 2020 22:49
Show Gist options
  • Save dongr0510/1436edcfc4a87343ca4c7846ab91c2f4 to your computer and use it in GitHub Desktop.
Save dongr0510/1436edcfc4a87343ca4c7846ab91c2f4 to your computer and use it in GitHub Desktop.
def can_partition(num):
s = sum(num)
dp = [[-1 for x in range(s+1)] for y in range(len(num))]
return can_partition_recursive(dp, num, 0, 0, 0)
def can_parition_recursive(dp, num, currentIndex, sum1, sum2):
# base check
if currentIndex == len(num):
return abs(sum1 - sum2)
# check if we have not already processed similar problem
if dp[currentIndex][sum1] == -1:
# recursive call after including the number at the currentIndex in the first set
diff1 = can_partition_recursive(
dp, num, currentIndex + 1, sum1 + num[currentIndex], sum2)
# recursive call after including the number at the currentIndex in the second set
diff2 = can_partition_recursive(
dp, num, currentIndex + 1, sum1, sum2 + num[currentIndex])
dp[currentIndex][sum1] = min(diff1, diff2)
return dp[currentIndex][sum1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment