-
Notifications
You must be signed in to change notification settings - Fork 0
39. Combination Sum #46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| max_usage = (target - total) / candidates[index] | ||
| (1..max_usage).each do |i| | ||
| new_total = total + candidates[index] * i | ||
| i.times { partial_combination << candidates[index] } | ||
| combination_sum_helper.call(index + 1, new_total, partial_combination) | ||
| i.times { partial_combination.pop } | ||
| end | ||
| combination_sum_helper.call(index + 1, total, partial_combination) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ループで毎回 partial_combination へ追加と削除しているのが気になりました。せっかく max_usage を求めているので、ループ内で一つ追加して、ループを抜けた時に max_usage 回 pop したら簡潔になると思いました。candidates[index] を 0 回使うとしてまとめる書き方もあるかもしれません。
combination_sum_helper.call(index + 1, total, partial_combination)
max_usage = (target - total) / candidates[index]
(1..max_usage).each do |i|
total += candidates[index]
partial_combination << candidates[index]
combination_sum_helper.call(index + 1, total, partial_combination)
end
max_usage.times { partial_combination.pop }There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
コメントありがとうございます!
こちらの方が簡潔で良いですね。
# @param {Integer[]} candidates
# @param {Integer} target
# @return {Integer[][]}
def combination_sum(candidates, target)
combinations = []
combination_sum_helper = lambda do |index, total, partial_combination|
if total == target
combinations << partial_combination.dup
return
end
return unless index < candidates.size
combination_sum_helper.call(index + 1, total, partial_combination)
max_usage = (target - total) / candidates[index]
(1..max_usage).each do |i|
total += candidates[index]
partial_combination << candidates[index]
combination_sum_helper.call(index + 1, total, partial_combination)
end
max_usage.times { partial_combination.pop }
end
combination_sum_helper.call(0, 0, [])
combinations
end| end | ||
| end | ||
| combination_sum_helper.call(0, 0, []) | ||
| combinations |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
いいと思います。個人的にはB を一つ使うか、C 以降しか使ってはいけないか、に分岐するやり方が一番読みやすいと思いました。
解いた問題
39. Combination Sum
使用言語
Ruby
次に解く問題
https://leetcode.com/problems/generate-parentheses/description/