leetcode78 subset

本文介绍了一种生成给定整数集合所有可能子集的方法,并通过递归深度优先搜索实现。此外,还讨论了如何计算两个整数之间的汉明距离,即对应位不同的数量,提供了一个简洁的实现方案。

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

If nums = [1,2,3], a solution is: [ ] [1]...

这个例子简单一看就能明白提议,一说求子集首先就会想到图的算法,这里的节点都是数字,有点儿巧妙哦,

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        self.dfs(nums,0,[],res)
        return res
    def dfs(self,nums,index,path,res):
        nums.sort()
        res.append(path)
        for i in range(index,len(nums)):#托了数字节点的福,这里的rang有讲究哦
            self.dfs(nums,i+1,path+[nums[i]],res)

也有人用Bit Manipulation ,学习学习

首先之前的开胃菜是,是标记easy的 hamming distance求法,然鹅,我并不会有代码实现,现在想想还是以前卷面考试来的好

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x^y).count('1') #bin 返回(x XOR y)操作的二进制,count统计1就好了,说实话,我是想不到这个异或操作的

顺便来个求补码的方法:

class Solution(object):
    def hammingDistance(self, x):

i=1

while i<=x:

i=i<<1 #左移

return ((i-1)^x)

Bit Manipulation:

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        nums.sort()
        for i in range(1<<len(nums)):
            tmp=[]
            for j in range(len(nums)):
                if i & 1<<j: #这个与操作为啥??一到这种还有字符串的东西,我就很懵

                    tmp.append(nums[j])
            res.append(tmp)
        return res



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值