Skip to content

Create 39. Combination Sum.md#52

Open
tokuhirat wants to merge 1 commit intomainfrom
39.-Combination-Sum
Open

Create 39. Combination Sum.md#52
tokuhirat wants to merge 1 commit intomainfrom
39.-Combination-Sum

Conversation

@tokuhirat
Copy link
Owner

This Problem
39. Combination Sum
Next Ploblem
22. Generate Parentheses
言語: Python

results = []

def generate_combination(index: int, combination: list[int]) -> None:
if sum(combination) == target:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

合計値も再帰関数の引数にして引き回す書き方もできますね。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

以下のような感じですね。個人的には、実行時間が問題ないのであれば、重複した情報は省いてコードを簡潔にしたいので 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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

同じ index の数字が繰り返して使用される場合は同処理しているんだろう (index + 1 でしか再帰関数を呼ばないので) と少し考えてしまいました。num が index の示す値でしたね。
この書き方がわかりにくいとは思いませんが、generate_combination を index と index + 1 それぞれに対して呼んでもいいと思います (個人的にはそちらのほうが手での走査 - 最初のインデックスから直線的に処理する - に近く好みではありますが、どちらが絶対良いというわけではないかと思います)。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

考え方の違いで遷移の分類が色々あるところで面白いですね。
私は index と index + 1 を呼ぶコードを読んだ時に少し考えてしまいました。
ある数字を使うパターンは先に処理して index を一つ進めるのが関数の仕事とした方が個人的にしっくりきました(手作業の場合でも)。
どちらでも良いと思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants