LeetCode知识点总结 - 78
LeetCode 78. Subsets
考点 | 难度 |
---|---|
Array | Medium |
题目
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.
思路
backtracking: an algorithm for finding all solutions by exploring all potential candidates. If the solution candidate turns to be not a solution (or at least not the last one), backtracking algorithm discards it by making some changes on the previous step, i.e. backtracks and then try again.
function backtrack(first, curr)
的作用是给定subset的长度,找到所有这个长度的subset。
对于一个combination,如果没有达到要求的长度就加element到这个combination。找到一个符合的subset后把这个subset append到array里,然后backtrack(pop掉最后一个数)再继续找其他subset。first
指的是新加入的第一个element的index。
k的范围是range(n + 1)
,因为subset的长度可以从0
到n
。
答案
简单的方法:
class Solution:
def subsets(self, nums):
result = [[]]
for number in nums:
for i in result:
# append (i in result list + number) to result list
result = result +[i + [number]]
return result
backtrack:
class Solution:
def subsets(self, nums):
def backtrack(first = 0, curr = []):
# if the combination is done
if len(curr) == k:
output.append(curr[:])
return
for i in range(first, n):
# add nums[i] into the current combination
curr.append(nums[i])
# use next integers to complete the combination
backtrack(i + 1, curr)
# backtrack
curr.pop()
output = []
n = len(nums)
for k in range(n + 1):
backtrack()
return output