Skip to content

Instantly share code, notes, and snippets.

@msg7086
Last active February 20, 2022 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msg7086/744d4cf2d81b42e27cb73069ecff939d to your computer and use it in GitHub Desktop.
Save msg7086/744d4cf2d81b42e27cb73069ecff939d to your computer and use it in GitHub Desktop.
# @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