Partition problem | DP | Returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; calculate sum of all elements ; initialize top row as true ; initialize leftmost column , except part [ 0 ] [ 0 ] , as 0 ; fill the partition table in bottom up manner ; uncomment this part to print table ; Driver Code ; Function call
def findPartition ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE i , j = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if sum % 2 != 0 : NEW_LINE INDENT return false NEW_LINE DEDENT part = [ [ True for i in range ( n + 1 ) ] for j in range ( sum // 2 + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT part [ 0 ] [ i ] = True NEW_LINE DEDENT for i in range ( 1 , sum // 2 + 1 ) : NEW_LINE INDENT part [ i ] [ 0 ] = False NEW_LINE DEDENT for i in range ( 1 , sum // 2 + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT part [ i ] [ j ] = part [ i ] [ j - 1 ] NEW_LINE if i >= arr [ j - 1 ] : NEW_LINE INDENT part [ i ] [ j ] = ( part [ i ] [ j ] or part [ i - arr [ j - 1 ] ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return part [ sum // 2 ] [ n ] NEW_LINE DEDENT arr = [ 3 , 1 , 1 , 2 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE if findPartition ( 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