今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

LeetCode 78. Subsets

ryo ariyama 2026年07月14日 20:36 0 次阅读 来源:Dev.to

Link https://leetcode.com/problems/subsets/description/ Problem Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example Example 1: Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: Input: nums = [0] Output: [[],[0]] Solution First, create a variable subsets, initialized to [[]], as the return value. Loop through nums, and for each element, create new subsets by appending that element to each existing subset. Then, append these new subsets to subsets. Sample code class Solution : def subsets ( self , nums : List [ int ]) -> List [ List [ int ]]: """ 0: [[]] 1: [[]]+[1] -> [[], [1]] 2: [[],[1]] + [2],[1,2] -> [[], [1], [2], [1, 2]] 3: [[], [1], [2], [1, 2]] + [3], [1, 3], [2, 3], [1,2,3] -> [[], [1], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] """ subsets = [[]] for num in nums : new_subsets = [ subset + [ num ] for subset in subsets ] subsets += new_subsets return subsets

本文内容来源于互联网,版权归原作者所有
查看原文