Conversation
| 分割数 | ||
| https://github.com/Mike0121/LeetCode/pull/1#discussion_r1578212926 | ||
|
|
||
| > 答えの数ですが、candidates = [1..target] の場合、これは分割数というものですね。 |
There was a problem hiding this comment.
There was a problem hiding this comment.
なるほど、この式だけなら理解できました。b[i+1] = a[i+1] - a[i]となるので、微分が現れるのですね。
あとは分割数が\sqrt{n}乗ということは何となく覚えておこうと思います。
| sorted_candidates = sorted(candidates) | ||
| combinations = [] | ||
|
|
||
| def get_combination(seen, combination, current_sum): |
There was a problem hiding this comment.
seenは、visitedのような再訪阻止の変数を期待してしまう気がしました。(すでに見た(seen)場所というより、これからの注目場所のような気が、、、)
なので、index, from_indexみたいな感じとかどうでしょうか。
There was a problem hiding this comment.
好みですが、currentはなくても良いかもしれません。今注目しているものは無印でも問題ないと思います。(sumだと、built-inと被るので、totalが好きです)
There was a problem hiding this comment.
seenは、visitedのような再訪阻止の変数を期待してしまう気がしました
そうですね、他には start としている方が多かったです。from_indexを採用させていただきました。
currentはなくても良いかもしれません
この変数名にしたのは sum が built-in とかぶってしまうからだったのですが、total は良さそうです。
変数名としての total は汎用性が高そうです。覚えておきます。
| if next_sum >= target: | ||
| if next_sum == target: | ||
| combinations.append(combination.copy()) | ||
| combination.pop() | ||
| return |
There was a problem hiding this comment.
L.13のifブロックは魚拓をとって終了する処理なので、再帰関数の直下で行うのが好みですかね。
下記の機械の例が参考になるかもです。
https://discord.com/channels/1084280443945353267/1192728121644945439/1194203372115464272
再帰関数のメインの処理がどこかのかを、わかりやすく主張したい気持ちがあります。
There was a problem hiding this comment.
なるほど、素直に読めるように書くべきですね。 if...else...で書き直してみました。
There was a problem hiding this comment.
コメントの意図としてはこういうイメージでした。
returnで終わる終了条件を再帰関数の下に並べる+その後にメインのバックトラックの処理を書く、という感じです。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
all_combinations = []
def collect_combs(comb, index, total) -> None:
if total == target:
all_combinations.append(comb[:])
return
if total > target:
return
if index >= len(candidates):
return
collect_combs(comb, index + 1, total)
comb.append(candidates[index])
collect_combs(comb, index, total + candidates[index])
comb.pop()
collect_combs([], 0, 0)
return all_combinationsThere was a problem hiding this comment.
まあ、今回で言うと next_sum のような、次の地点や担当者のことを考えるのは、BFSで有効(最初の到達で最短距離確定するため)だったり、枝刈りになったりしそうなので、考え方としては良いものなのではとは思っています。
There was a problem hiding this comment.
なるほど、index + 1でも再帰を行えばfor文が不要になりますね。こちらも残しておきます。
| frontier = [(0, 0, [])] | ||
|
|
||
| while frontier: | ||
| current_sum, seen, elments = frontier.pop() |
There was a problem hiding this comment.
細かいところまで見ていただいて、ありがとうございます
https://leetcode.com/problems/combination-sum/description/