Skip to content

solve: 78.Subsets#51

Open
t9a-dev wants to merge 1 commit intomainfrom
78.Subsets
Open

solve: 78.Subsets#51
t9a-dev wants to merge 1 commit intomainfrom
78.Subsets

Conversation

@t9a-dev
Copy link
Owner

@t9a-dev t9a-dev commented Feb 7, 2026

問題: 78. Subsets
次に解く問題: 39. Combination Sum
ファイルの構成: ./src/bin/<各ステップ>.rs


for (i, num) in nums.iter().enumerate() {
subset.push(*num);
all_subsets.extend(Self::make_subsets(&nums[i + 1..], subset));
Copy link

Choose a reason for hiding this comment

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

ここ、extend で shallow copy (move)発生という理解でいいですか?

make_subsets にもう一つ引数を増やし、与えられた最後の引数に結果を extend する関数とするとこの問題は解決しますね。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ここ、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)になるとのことだった。
Copy link

Choose a reason for hiding this comment

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

nが10で log n と n では4倍くらいしか違わないはずです。

が、GPT-5.2 のその計算量評価は間違いでしょう。

f(n) = cost(sort(n)) + n * (cost(clone(n-1)) + f(n - 1)) となっているので、sort と clone 部分は最後定数になるはずです。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
f(n) = cost(sort(n)) + n * (cost(clone(n-1)) + f(n - 1)) のとき、n * f(n - 1)の部分が支配的であるので時間計算量はO(n!)になると理解しました。

Copy link

Choose a reason for hiding this comment

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

そうですね。具体的に代入してみれば明らかに感じるでしょう。

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