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