Skip to content

Conversation

@Fuminiton
Copy link
Owner

candidate.pop()

return permutations
```
Copy link

Choose a reason for hiding this comment

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

読みやすいです。
分かりやすさとのトレードオフはありそうですが、下のようにindexを引数にとる感じでヘルパー関数を定義してバックトラッキングを行うようなやり方もよく見ます。構成してきた順列と使っていない要素を一緒に一つの配列で管理できるようになり、if num in candidate:で弾く必要がなくなるので、多少効率的になるかもしれません。

def permuteHelper(i):
    if i == len(nums): # len(nums) - 1 でも動くかも
        permutations.append(nums[:])
        return
    for j in range(i, len(nums)):
        nums[i], nums[j] = nums[j], nums[i]
        permuteHelper(i + 1)
        nums[i], nums[j] = nums[j], nums[i]

Copy link
Owner Author

Choose a reason for hiding this comment

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

レビュー、代替案のご提示ありがとうございます。

  1. 0番目を固定して、0番目に入れ替えられるパターンを列挙する
  2. 0,1番目を固定して、1番目以降の要素で入れ替えられるパターンを列挙する
  3. 0,1,2番目を.....

という流れで組み合わせを列挙できる規則を利用するのですね。
気づけていなかったです。ありがとうございます!

Comment on lines +141 to +143
candidates = []
for num in nums:
candidates.append([num])

Choose a reason for hiding this comment

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

candidates = [[]] でも良いと思いました。

Copy link
Owner Author

@Fuminiton Fuminiton Oct 25, 2025

Choose a reason for hiding this comment

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

レビューありがとうございます。
candidateに何かを入れておかねばという意識が先行してnumを入れていましたが、おっしゃる通り[]を入れておくでも問題ないですね。


### 感想
- これまで使っているnumsの要素が入っているという意味でusedと命名していたが、candidate の方が実体に近いので変えるべき
- itertools.permutationsは読みづらかった。というか理解できていないので、時間をおいて読む

Choose a reason for hiding this comment

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

https://github.com/tokuhirat/LeetCode/pull/50/files#diff-f980f45b4d4f94c41556977f060a371872f422650416425386f1322e52deba58R88
itertools.permutations のコードにコメントをつけてみたので、ご参考になればと思います。

return
for num in nums:
if num in used:
continue
Copy link

Choose a reason for hiding this comment

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

num in used の時間計算量が線形のため、全体の計算量が O(n^2n!) になるように思いました。 used 以外に set を持たせると、時間計算量が O(nn!) に落ちると思いました。

Copy link
Owner Author

@Fuminiton Fuminiton Oct 25, 2025

Choose a reason for hiding this comment

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

レビューありがとうございます。
if num in usedの考慮が漏れていました。
おっしゃる通りO(n^2 * n!)が正しいですね。

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.

5 participants