Skip to content

Commit 7c1359b

Browse files
committed
partitiona equal subset
1 parent 0566a4e commit 7c1359b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* lc416 (https://leetcode.com/problems/partition-equal-subset-sum/)
3+
* Given a non-empty array containing only positive integers,
4+
* find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
5+
* @param {number[]} nums
6+
* @return {boolean}
7+
*/
8+
var canPartition = function (nums) {
9+
const sum = nums.reduce((acc, num) => acc + num, 0);
10+
if (sum % 2 === 1) {
11+
return false;
12+
}
13+
14+
const half = sum / 2;
15+
16+
const dp = [];
17+
for (let i = 0; i <= nums.length; i++) {
18+
dp[i] = [];
19+
dp[i][0] = true;
20+
}
21+
22+
for (let j = 0; j <= half; j++) {
23+
dp[0][j] = false;
24+
}
25+
dp[0][0] = true;
26+
27+
for (let i = 1; i <= nums.length; i++) {
28+
for (let j = 1; j <= half; j++) {
29+
dp[i][j] = dp[i - 1][j];
30+
if (nums[i - 1] <= j) {
31+
dp[i][j] = (dp[i - 1][j - nums[i - 1]] || dp[i][j]);
32+
}
33+
}
34+
}
35+
36+
return dp[nums.length][half];
37+
};

0 commit comments

Comments
 (0)