Skip to content

Commit 82dc497

Browse files
Merge pull request akshitagit#174 from gargi-agrawal/master
Dynamic Programming - Subset Sum Problem
2 parents 1553504 + c60bd4e commit 82dc497

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

DynamicProgramming/Subset_sum.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Problem Statement -
3+
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.
4+
5+
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
6+
Output: True
7+
8+
*/
9+
10+
// Returns true if there is a subset of set[] with sum equal to given sum
11+
function isSubsetSum(set, n, sum)
12+
{
13+
// Value of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i
14+
let subset = new Array(sum + 1);
15+
16+
for(let i = 0; i < sum + 1; i++)
17+
{
18+
subset[i] = new Array(sum + 1);
19+
for(let j = 0; j < n + 1; j++)
20+
{
21+
subset[i][j] = 0;
22+
}
23+
}
24+
25+
// If sum is 0, then answer is true
26+
for (let i = 0; i <= n; i++)
27+
subset[0][i] = true;
28+
29+
// If sum is not 0 and set is empty, then answer is false
30+
for (let i = 1; i <= sum; i++)
31+
subset[i][0] = false;
32+
33+
// Fill the subset table in bottom up manner
34+
for (let i = 1; i <= sum; i++) {
35+
for (let j = 1; j <= n; j++) {
36+
subset[i][j] = subset[i][j - 1];
37+
if (i >= set[j - 1])
38+
subset[i][j] = subset[i][j]
39+
|| subset[i - set[j - 1]][j - 1];
40+
}
41+
}
42+
43+
return subset[sum][n];
44+
}
45+
46+
let set = [ 3, 34, 4, 12, 5, 2 ];
47+
let sum = 9;
48+
let n = set.length;
49+
if (isSubsetSum(set, n, sum) == true)
50+
document.write("Found a subset" + " with given sum");
51+
else
52+
document.write("No subset with" + " given sum");

0 commit comments

Comments
 (0)