LeetCode知识点总结 - 78

LeetCode 78. Subsets

考点难度
ArrayMedium
题目

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的长度可以从0n

答案

简单的方法:

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值