Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.
Example:
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True //There is a subset (4, 5) with sum 9.
We can solve the problem in Pseudo-polynomial time using Dynamic programming. We create a boolean 2D table subset[][] and fill it in bottom up manner. The value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i., otherwise false. Finally, we return subset[sum][n]
#include <stdio.h>
bool
isSubsetSum(
int
set[],
int
n,
int
sum)
{
bool
subset[n+1][sum+1];
for
(
int
i = 0; i <= n; i++)
subset[i][0] =
true
;
for
(
int
i = 1; i <= sum; i++)
subset[0][i] =
false
;
for
(
int
i = 1; i <= n; i++)
{
for
(
int
j = 1; j <= sum; j++)
{
if
(j<set[i-1])
subset[i][j] = subset[i-1][j];
if
(j >= set[i-1])
subset[i][j] = subset[i-1][j] ||
subset[i - 1][j-set[i-1]];
}
}
return
subset[n][sum];
}
int
main()
{
int
set[] = {3, 34, 4, 12, 5, 2};
int
sum = 9;
int
n =
sizeof
(set)/
sizeof
(set[0]);
if
(isSubsetSum(set, n, sum) ==
true
)
printf
(
"Found a subset with given sum"
);
else
printf
(
"No subset with given sum"
);
return
0;
}
class GFG {
static boolean isSubsetSum( int set[],
int n, int sum)
{
boolean subset[][] =
new boolean [sum+ 1 ][n+ 1 ];
for ( int i = 0 ; i <= n; i++)
subset[ 0 ][i] = true ;
for ( int i = 1 ; i <= sum; i++)
subset[i][ 0 ] = false ;
for ( int i = 1 ; i <= sum; i++)
{
for ( int j = 1 ; j <= n; j++)
{
subset[i][j] = subset[i][j- 1 ];
if (i >= set[j- 1 ])
subset[i][j] = subset[i][j] ||
subset[i - set[j- 1 ]][j- 1 ];
}
}
return subset[sum][n];
}
public static void main (String args[])
{
int set[] = { 3 , 34 , 4 , 12 , 5 , 2 };
int sum = 9 ;
int n = set.length;
if (isSubsetSum(set, n, sum) == true )
System.out.println( "Found a subset"
+ " with given sum" );
else
System.out.println( "No subset with"
+ " given sum" );
}
}
|
Output:
Found a subset with given sum
Time complexity of the above solution is O(sum*n).
def isSubsetSum( set ,n, sum ):
subset = ([[ False for i in range ( sum + 1 )]
for i in range (n + 1 )])
for i in range (n + 1 ):
subset[i][ 0 ] = True
for i in range ( 1 , sum + 1 ):
subset[ 0 ][i] = False
for i in range ( 1 ,n + 1 ):
for j in range ( 1 , sum + 1 ):
if j< set [i - 1 ]:
subset[i][j] = subset[i - 1 ][j]
if j> = set [i - 1 ]:
subset[i][j] = (subset[i - 1 ][j] or
subset[i - 1 ][j - set [i - 1 ]])
return subset[n][ sum ]
if __name__ = = '__main__' :
set = [ 3 , 34 , 4 , 12 , 5 , 2 ]
sum = 9
n = len ( set )
if (isSubsetSum( set , n, sum ) = = True ):
print ( "Found a subset with given sum" )
else :
print ( "No subset with given sum" )
|
Output:
Found a subset with given sum
Time complexity of the above solution is O(sum*n).
https://www.youtube.com/watch?v=dJmyfFC3-3A
Comments
Post a Comment