LeetCode 46全排列代码报TypeError错误,请求问题排查
解决LeetCode 46. Permutations中的TypeError问题
错误原因
- Python列表的
insert()方法是原地修改操作,返回值为None。你的代码中将insert()的返回值赋值给t,再把t添加到temp列表,导致temp里全是None。 - 进入下一轮循环时,遍历
ans(此时ans是上一轮的temp),对None类型的elt调用len(elt),就触发了TypeError: object of type 'NoneType' has no len()。
修复后的代码
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: ans = [[]] for i in range(len(nums)): temp = [] for elt in ans: for j in range(len(elt)+1): local = elt.copy() local.insert(j, nums[i]) temp.append(local) ans = temp.copy() return ans
说明
直接调用local.insert(j, nums[i])修改列表,不需要接收返回值,之后将修改后的local添加到temp中,这样temp里存储的都是有效的排列子列表,后续循环就能正常执行。
内容的提问来源于stack exchange,提问作者eppysilon
相关产品推荐
相关产品推荐

