Dynamic Programming | Returns true if there is a subset of set [ ] 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 ; Driver code
def isSubsetSum ( set , n , sum ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( set [ n - 1 ] > sum ) : NEW_LINE INDENT return isSubsetSum ( set , n - 1 , sum ) NEW_LINE DEDENT return isSubsetSum ( set , n - 1 , sum ) or isSubsetSum ( set , n - 1 , sum - set [ n - 1 ] ) NEW_LINE DEDENT set = [ 3 , 34 , 4 , 12 , 5 , 2 ] NEW_LINE sum = 9 NEW_LINE n = len ( set ) NEW_LINE if ( isSubsetSum ( set , n , sum ) == True ) : NEW_LINE INDENT print ( " Found ▁ a ▁ subset ▁ with ▁ given ▁ sum " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ subset ▁ with ▁ given ▁ sum " ) NEW_LINE DEDENT