Partition problem | DP | A utility function that returns true if there is a subset of arr [ ] with sun equal to given sum ; Base Cases ; If last element is greater than sum , then ignore it ; else , check if sum can be obtained by any of the following ( a ) including the last element ( b ) excluding the last element ; Returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; Calculate sum of the elements in array ; If sum is odd , there cannot be two subsets with equal sum ; Find if there is subset with sum equal to half of total sum ; Driver code ; Function call
def isSubsetSum ( arr , n , sum ) : NEW_LINE INDENT if sum == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if n == 0 and sum != 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if arr [ n - 1 ] > sum : NEW_LINE INDENT return isSubsetSum ( arr , n - 1 , sum ) NEW_LINE DEDENT return isSubsetSum ( arr , n - 1 , sum ) or isSubsetSum ( arr , n - 1 , sum - arr [ n - 1 ] ) NEW_LINE DEDENT def findPartion ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if sum % 2 != 0 : NEW_LINE INDENT return false NEW_LINE DEDENT return isSubsetSum ( arr , n , sum // 2 ) NEW_LINE DEDENT arr = [ 3 , 1 , 5 , 9 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE if findPartion ( arr , n ) == True : NEW_LINE INDENT print ( " Can ▁ be ▁ divided ▁ into ▁ two ▁ subsets ▁ of ▁ equal ▁ sum " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Can ▁ not ▁ be ▁ divided ▁ into ▁ two ▁ subsets ▁ of ▁ equal ▁ sum " ) NEW_LINE DEDENT