Number of subsets with zero sum | Python3 implementation of above approach ; variable to store states of dp ; To find the number of subsets with sum equal to 0. Since S can be negative , we will maxSum to it to make it positive ; Base cases ; Returns the value if a state is already solved ; If the state is not visited , then continue ; Recurrence relation ; Returning the value ; Driver Code
import numpy as np NEW_LINE maxSum = 100 NEW_LINE arrSize = 51 NEW_LINE dp = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE visit = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE def SubsetCnt ( i , s , arr , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( s == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( visit [ i ] [ s + arrSize ] ) : NEW_LINE INDENT return dp [ i ] [ s + arrSize ] ; NEW_LINE DEDENT visit [ i ] [ s + arrSize ] = 1 ; NEW_LINE dp [ i ] [ s + arrSize ] = ( SubsetCnt ( i + 1 , s + arr [ i ] , arr , n ) + SubsetCnt ( i + 1 , s , arr , n ) ) ; NEW_LINE return dp [ i ] [ s + arrSize ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 2 , 2 , - 4 , - 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( SubsetCnt ( 0 , 0 , arr , n ) ) ; NEW_LINE DEDENT