您的位置:首页 > 编程语言 > Python开发

LeetCode 78. Subsets--Python实现

2018-01-29 17:24 459 查看
Given a set of distinct integers, nums, return all possible subsets (the power set).Note: The solution set must not contain duplicate subsets.For example,
If nums = 
[1,2,3]
, a solution is:[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]本题主要有三个方法,具体的代码如下。第一个是动态规划的方法。
def subsets(self, nums): #43%,69ms
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = self.subset_func(nums)
for line in result:
line.sort()
return result

def subset_func(self,nums):
if len(nums)==0:
return [[]]
if len(nums)==1:
return [[],nums]
first = nums[0]
tmp_nums = nums[1:]
tmp_result = self.subset_func(tmp_nums)
result = []
for key in tmp_result: #动态规划的方法,result包括tmp_result的所有的,还包括tep_result都加上first
result.append(key)
tmp = list(key)
tmp.append(first)
result.append(tmp)
return result
第二个是中间变量的方法。 def subsets(self, nums): #43%,69ms
"""
:type nums: List[int]
:rtype: List[List[int]]
"""

res = [[]] #中间变量法
for num in nums :
for temp in res[:] : #这个地方为什么要用分片啊 Time Limit Exceeded,这个地方一定要带切片啊,调试时出现大bug啊,原因是如果不带分片,就是一个浅拷贝,后面res有变化,导致res不断增加,for循环一直进行下去啊
x = temp[:] #会改变原来的,浅拷贝x=temp
x.append(num)
res.append(x)
return res第三个是回溯的方法
def subsets(self, nums):  #43%,69ms
"""
:type nums: List[int]
:rtype: List[List[int]]
"""

res=[]               #回溯法
temp=[]
def dfs(nums,res,start,temp):
#x=copy.deepcopy(temp)
x=temp[:]
res.append(x)  #深拷贝与浅拷贝的问题,分片操作对多维数组来说也是浅拷贝啊
for i in range(start,len(nums)):
temp.append(nums[i])#添加第i个元素
dfs(nums,res,i+1,temp)
temp.remove(nums[i])#不添加
dfs(nums,res,0,temp) # res=dfs(nums,res,0,temp)
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: