78-子集

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。


示例

输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

解法

核心思想:利用回溯算法,每添加一个数字,加到res一次

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
# 回溯函数
def backtrack(index, tem):
res.append(tem)
for i in range(index,n):
backtrack(i+1, tem+[nums[i]])

backtrack(0, [])
return res

相关信息

LeetCode:Discussion | Solution

-------------本文结束感谢您的阅读-------------