我正在尝试解决 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]
Run Code Online (Sandbox Code Playgroud)
该代码确实产生了独特的组合,但是,当我运行它时,我收到此错误:
TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' object在curr.append(l[idx]).
如何解决这个问题?任何帮助,将不胜感激。
编辑:
我已经尝试了@user2357112 支持莫妮卡建议的内容并更改了我的代码:
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]
Run Code Online (Sandbox Code Playgroud)
现在错误消失了,但结果是空的:
[1, 1, 6]
[1, 2, 5]
[1, 7]
[2, 6]
result:
[[], [], [], []]
Run Code Online (Sandbox Code Playgroud)
正在创建组合,但未附加到结果中。
我无法弄清楚错误在哪里。任何帮助,将不胜感激。谢谢你。
小智 6
您可能正在使用deque,一旦我也遇到了同样的问题,错误是因为:您deque直接附加到 中(如果您正在使用它)而没有初始化列表。
容易出错的代码:
from collections import defaultdict, deque
d = defaultdict(lambda: deque)
a = [1, 2, 3]
for i in range(3):
d[a[i]].append(i)
Run Code Online (Sandbox Code Playgroud)
无错误代码:
from collections import defaultdict, deque
d = defaultdict(lambda: deque([])
Run Code Online (Sandbox Code Playgroud)
看看前面的错误说它不适用于 int 对象,实际上它不适用于任何东西,直到您在deque.
所以总的来说,总是像deque([]).
如果您在 python 类型(类)append上调用方法list而不是list.
>>> from typing import List
>>> l = list
>>> l.append
<method 'append' of 'list' objects>
>>> l.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'append' requires a 'list' object but received a 'int'
>>>
Run Code Online (Sandbox Code Playgroud)
如您所见,第一个参数是( )append类型的对象listself
class list(object):
"""
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
"""
def append(self, *args, **kwargs): # real signature unknown
""" Append object to the end of the list. """
pass
Run Code Online (Sandbox Code Playgroud)