Skip to content

Commit 3b93041

Browse files
authored
Update 416-partition-equal-subset-sum.js
1 parent a72c5c2 commit 3b93041

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

416-partition-equal-subset-sum.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,37 @@ const canPartition = function(nums) {
3434
}
3535
return dp[n][sum]
3636
};
37+
38+
// another
39+
40+
/**
41+
* @param {number[]} nums
42+
* @return {boolean}
43+
*/
44+
const canPartition = function(nums) {
45+
if (nums.length < 2) return false
46+
47+
const total = nums.reduce((a, c) => a + c)
48+
if (total % 2 !== 0) return false
49+
50+
nums.sort((a, b) => b - a)
51+
const target = total / 2
52+
53+
if (nums[0] > target) return false
54+
return findCombination(nums, target, 0)
55+
}
56+
57+
function findCombination(nums, target, start) {
58+
if (target === 0) {
59+
return true
60+
} else {
61+
for (let i = start; i < nums.length; i++) {
62+
if (nums[i] <= target) {
63+
if (findCombination(nums, target - nums[i], i + 1)) {
64+
return true
65+
}
66+
}
67+
}
68+
return false
69+
}
70+
}

0 commit comments

Comments
 (0)