第一种方法:递归 要不要第index元素,index到len(nums)
# https://www.lintcode.com/problem/17/
# 给定一个含不同整数的集合,返回其所有的子集(任意顺序)。
class Solution:
def subsets(self,nums):
# 特殊情况判断
if not nums:
return [[]]
nums.sort()
# 记录所有子集
result = []
self.dps(nums,0,[],result)
return result
# 1.递归的定义:
# nums -- 含不同整数的集合
# index -- 指示第index个元素
# combination -- index之前选择的结果
# result -- 返回其所有的子集结果
def dps(self,nums,index,combination,result):
# 2.递归出口
if index == len(nums):
# 深拷贝
result.append(list(combination))
return
# 递归的拆解
#选第 index 个元素
combination.append(nums[index])
self.dps(nums,index+1,combination,result)
#不选第 index 个元素
combination.pop()
self.dps(nums,index+1,combination,result)
return result
nums = [1,2,3,4]
print(Solution().subsets(nums))
运行结果:
C:\Users\lenovo\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/lenovo/PycharmProjects/pythonProject/main.py
[[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], []]
Process finished with exit code 0
另一种方法:bin(2**len(nums)) 二进制数位
100 101 110 111
011 010 001 000
from typing import (
List,
)
class Solution:
def subsets(self,nums):
if not nums:
return [[]]
nums.sort()
length = len(nums)
combinations = []
for numbers in range(2**(length-1),2**length):
strNum = bin(numbers)[2:]
combination = []
index = 0
for s in strNum:
if s == "0":
index +=1
if s == "1":
combination.append(nums[index])
index +=1
combinations.append(combination)
combination = []
index = 0
for s in strNum:
if s == "1":
index +=1
if s == "0":
combination.append(nums[index])
index +=1
combinations.append(combination)
return combinations