Last active
February 20, 2022 23:25
-
-
Save msg7086/744d4cf2d81b42e27cb73069ecff939d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @param {Integer[]} nums | |
# @return {Boolean} | |
def can_partition(nums) | |
sum = nums.sum | |
return false if sum.odd? | |
nums.sort! | |
nums.reverse! | |
half_sum = sum / 2 | |
dp = Set.new | |
0.upto(nums.size-1) do |i| | |
num = nums[i] | |
dp += dp.map { |x| x + num } | |
dp << num | |
return true if dp.include?(half_sum) | |
dp.delete_if { |x| x > half_sum} | |
end | |
false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment