【发布时间】:2020-06-30 04:26:28
【问题描述】:
我正在尝试解决 Python 中的 LeetCode 问题。给定一个整数列表和一个目标,我们必须在列表中找到所有唯一的整数组合,其总和等于目标。该列表可以有重复的整数,但整数的组合(其和等于目标)在结果中必须是唯一的。该列表将只有正整数https://leetcode.com/problems/combination-sum-ii/
下面是代码:
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
result = List[List[int]]
c = List[int]
self.combSum2(0,sorted(candidates),target,result,c)
return result
def combSum2(self, i: int, l: List[int], t: int, res: List[List[int]], curr: List[int]):
if t == 0:
print(curr)
res.append(curr)
return
if t < 0:
return
for idx in range(i,len(l):
if(idx == i or l[idx] != l[idx-1]):
curr.append(l[idx])
self.combSum2(idx+1,l,t-l[idx],res,curr)
del curr[-1]
代码确实产生了独特的组合,但是,当我运行它时,我收到了这个错误:
TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' object 在curr.append(l[idx]) 线上。
如何解决这个问题?任何帮助将不胜感激。
编辑:
我已经尝试了 @user2357112 支持的 Monica 建议并更改了我的代码:
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
c = []
self.combSum2(0,sorted(candidates),target,result,c)
print("result:")
print(result)
return result
def combSum2(self, i: int, l: List[int], t: int, res: [], curr: []):
if t == 0:
print(curr)
res.append(curr)
return
if t < 0:
return
for idx in range(i,len(l)):
if(idx == i or l[idx] != l[idx-1]):
curr.append(l[idx])
self.combSum2(idx+1,l,t-l[idx],res,curr)
del curr[-1]
现在错误消失但结果为空:
[1, 1, 6]
[1, 2, 5]
[1, 7]
[2, 6]
result:
[[], [], [], []]
正在创建组合,但没有附加到结果中。
我不知道错误在哪里。任何帮助,将不胜感激。谢谢。
【问题讨论】:
-
这是整个错误信息吗?
result = List[List[int]]是干什么用的? -
result用于存储来自candidates的整数的所有唯一组合。使用错误消息编辑问题。 @AMC -
result = List[List[int]]不会使result成为整数列表的列表。如果您想要一个空列表,请使用[]。List[List[int]]是用于类型注释的东西。 -
@user2357112supportsMonica 更新了我的问题。
-
是的,你有更多的错误。 (此外,您也不应该将类型注释更改为
[]。)
标签: python python-3.x