Skip to content

Commit cb388b2

Browse files
committed
Add solution #416
1 parent bed3836 commit cb388b2

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@
281281
412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy|
282282
414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy|
283283
415|[Add Strings](./0415-add-strings.js)|Easy|
284+
416|[Partition Equal Subset Sum](./0416-partition-equal-subset-sum.js)|Medium|
284285
419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium|
285286
434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy|
286287
435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 416. Partition Equal Subset Sum
3+
* https://leetcode.com/problems/partition-equal-subset-sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums, return true if you can partition the array into two subsets
7+
* such that the sum of the elements in both subsets is equal or false otherwise.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @return {boolean}
13+
*/
14+
var canPartition = function(nums) {
15+
const sum = nums.reduce((a, b) => a + b);
16+
if (sum % 2) {
17+
return false;
18+
}
19+
20+
const target = sum / 2;
21+
let set = new Set([0]);
22+
for (const n of nums) {
23+
const next = new Set(set);
24+
for (const value of set) {
25+
if (value + n === target) {
26+
return true;
27+
}
28+
next.add(value + n);
29+
}
30+
set = next;
31+
}
32+
33+
return false;
34+
};

0 commit comments

Comments
 (0)