You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:01:29