leetcode 78. 子集 使用itertools实现

leetcode 78. 子集 使用itertools.combinations实现

from itertools import combinations
from typing import List

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        # 结果列表,用来存放所有子集
        result = []
        # 遍历所有可能的子集长度,从 0 到 len(nums)
        for r in range(len(nums) + 1):
            # 对于每个长度 r,生成所有长度为 r 的组合
            comb_iter = combinations(nums, r)
            # 遍历所有生成的组合
            for comb in comb_iter:
                # 将元组转换为列表后添加到结果中
                result.append(list(comb))
        return result
posted @ 2025-03-25 16:11  null147  阅读(19)  评论(0)    收藏  举报