题目来源
https://leetcode.com/problems/subsets/
Given a set of distinct integers, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
题意分析
Input:
:type nums: List[int]
Output:
:rtype: List[List[int]]
Conditions: 给定一个没有重复元素的list,返回其所有的子集,注意每一个子集中的元素都是非降序的,子集不可以重复。
题目思路
用dfs的思路,每次增加一个数。因为事先将list排序了,所以下一次dfs时应该只遍历当前位置之后的元素。
AC代码(Python)
1 class Solution(object): 2 def subsets(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[List[int]] 6 """ 7 def dfs(depth, start, valueList): 8 res.append(valueList) 9 if depth == len(nums): 10 return 11 for i in range(start, len(nums)): 12 dfs(depth + 1, i + 1, valueList+[nums[i]]) 13 14 nums.sort() 15 res = [] 16 dfs(0, 0, []) 17 return res
时间: 2024-11-12 09:19:55