leetcode78 subset
来源:互联网 发布:数据电视怎么调画面 编辑:程序博客网 时间:2024/05/20 09:45
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 = 4Output: 2Explanation: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
- leetcode78 subset
- LeetCode78/90 subset I/II**
- LeetCode78
- LeetCode78:Subsets
- LeetCode78. Subsets
- leetcode78. Subsets
- leetcode78. Subsets
- LeetCode78 SubSets
- subset
- Subset
- Subset
- Subset
- subset
- subset
- subset
- LeetCode78——Subsets
- 【leetcode78】Single Number II
- LeetCode78. Subsets java solution
- STM32 端口复用&重映射(USART Remap)
- 基于HTML5 Canvas实现用户交互
- js中Uncaught RangeError: Maximum call stack size exceeded问题
- spring4.0整合了validation验证功能
- HTML CSS JS 思维导图
- leetcode78 subset
- rabbmitmq安装笔记
- linux tar.gz zip 解压缩 压缩命令
- Future的使用
- 09、vue.js 之自定义指令
- HashMap要点记
- java.lang.IllegalArgumentException: Scrapped or attached views may not be recycled. isScrap:false is
- 数据库事务隔离级别-- 脏读、幻读、不可重复读(清晰解释)
- JUnit自动化单元测试(五):参数化测试