Conversation
ryosuketc
reviewed
Aug 17, 2025
| results = [] | ||
|
|
||
| def generate_combination(index: int, combination: list[int]) -> None: | ||
| if sum(combination) == target: |
Owner
Author
There was a problem hiding this comment.
以下のような感じですね。個人的には、実行時間が問題ないのであれば、重複した情報は省いてコードを簡潔にしたいので sum は各関数で計算するようにしていました。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
results = []
def generate_combination(index: int, combination: list[int], sum_: int) -> None:
if sum_ == target:
results.append(combination)
return
if index >= len(candidates):
return
num = candidates[index]
new_combination = combination[:]
while sum_ <= target:
generate_combination(index + 1, new_combination[:], sum_)
new_combination.append(num)
sum_ += num
generate_combination(0, [], 0)
return results
Comment on lines
+121
to
+124
| while sum_ <= target: | ||
| generate_combination(index + 1, new_combination[:]) | ||
| sum_ += num | ||
| new_combination.append(num) |
There was a problem hiding this comment.
同じ index の数字が繰り返して使用される場合は同処理しているんだろう (index + 1 でしか再帰関数を呼ばないので) と少し考えてしまいました。num が index の示す値でしたね。
この書き方がわかりにくいとは思いませんが、generate_combination を index と index + 1 それぞれに対して呼んでもいいと思います (個人的にはそちらのほうが手での走査 - 最初のインデックスから直線的に処理する - に近く好みではありますが、どちらが絶対良いというわけではないかと思います)。
Owner
Author
There was a problem hiding this comment.
考え方の違いで遷移の分類が色々あるところで面白いですね。
私は index と index + 1 を呼ぶコードを読んだ時に少し考えてしまいました。
ある数字を使うパターンは先に処理して index を一つ進めるのが関数の仕事とした方が個人的にしっくりきました(手作業の場合でも)。
どちらでも良いと思います。
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This Problem
39. Combination Sum
Next Ploblem
22. Generate Parentheses
言語: Python