Skip to content

Commit 6c5274a

Browse files
committed
add partition equal subset sum
1 parent 954adff commit 6c5274a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Given a non-empty array nums containing only positive integers,
2+
// find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
3+
var canPartition = function (nums) {
4+
if (!nums) return false;
5+
let total = nums.reduce((a, b) => a + b, 0);
6+
7+
if (total % 2 != 0) return false;
8+
9+
let target = total / 2;
10+
let arr = new Array(target + 1).fill(false);
11+
arr[0] = true;
12+
13+
for (let el of nums) {
14+
for (let i = target; i >= 0; i--) {
15+
let complement = i - el;
16+
17+
if (!arr[i] && arr[complement]) {
18+
arr[i] = true;
19+
}
20+
if (arr[target] == true) return true;
21+
}
22+
}
23+
24+
return false;
25+
};

0 commit comments

Comments
 (0)