Open
Conversation
oda
reviewed
Feb 8, 2026
|
|
||
| for (i, num) in nums.iter().enumerate() { | ||
| subset.push(*num); | ||
| all_subsets.extend(Self::make_subsets(&nums[i + 1..], subset)); |
There was a problem hiding this comment.
ここ、extend で shallow copy (move)発生という理解でいいですか?
make_subsets にもう一つ引数を増やし、与えられた最後の引数に結果を extend する関数とするとこの問題は解決しますね。
Owner
Author
There was a problem hiding this comment.
ここ、extend で shallow copy (move)発生という理解でいいですか?
はい。Self::make_subsetsの結果をmoveしています。
make_subsets にもう一つ引数を増やし、与えられた最後の引数に結果を extend する関数とするとこの問題は解決しますね。
副作用で引数に変更を加えていくと理解しました。
impl Solution {
pub fn subsets(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut all_subsets = Vec::new();
Self::make_subsets(&nums, &mut Vec::new(), &mut all_subsets);
all_subsets
}
fn make_subsets(nums: &[i32], subset: &mut Vec<i32>, all_subsets: &mut Vec<Vec<i32>>) {
all_subsets.extend(vec![subset.to_vec()]);
for (i, num) in nums.iter().enumerate() {
subset.push(*num);
Self::make_subsets(&nums[i + 1..], subset, all_subsets);
subset.pop();
}
}
}| - 重複する配列を結果に含めずに処理するアルゴリズム | ||
|
|
||
| 正解してから気づいたこと | ||
| - 時間計算量の見積もりが不安だったのでGPT-5.2に聞いたところ正確にはsortの時間計算量よりも、make_subsets内のforループでcloneしているコストの方が大きくO(n! * n ^ 2)になるとのことだった。 |
There was a problem hiding this comment.
nが10で log n と n では4倍くらいしか違わないはずです。
が、GPT-5.2 のその計算量評価は間違いでしょう。
f(n) = cost(sort(n)) + n * (cost(clone(n-1)) + f(n - 1)) となっているので、sort と clone 部分は最後定数になるはずです。
Owner
Author
There was a problem hiding this comment.
ありがとうございます。
f(n) = cost(sort(n)) + n * (cost(clone(n-1)) + f(n - 1)) のとき、n * f(n - 1)の部分が支配的であるので時間計算量はO(n!)になると理解しました。
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.
問題: 78. Subsets
次に解く問題: 39. Combination Sum
ファイルの構成:
./src/bin/<各ステップ>.rs