不同整数的集合,返回其所有的子集

第一种方法:递归 要不要第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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值