Python - WA while using list.pop(), AC while using list = list[:-1]


  • 0
    A

    I don't understand it. This is my AC code.

    class Solution:
    # @param {integer[]} nums
    # @return {integer[][]}
    
    def permute(self, nums):
        ans = []
        self.tmp = []
        n = len(nums)
        self.dfs(n, 0, [False]*n,nums, ans)
        return ans
        
    def dfs(self, n, p, visit, nums, ans):
        if n == p:
            ans.append(self.tmp)
            return
        
        for i in range(n):
            if visit[i]:
                continue
            visit[i] = True
            self.tmp.append(nums[i])
            self.dfs(n, p+1, visit, nums, ans)
            self.tmp = self.tmp[:-1]
            visit[i] = False
    
        return
    

    When I used self.tmp.pop() intead of self.tmp = self.tmp[:-1],
    I will get WA. But I though it has the same effect in my code..
    Can anyone help me with that?


  • 0
    L

    When you use pop, the list will return the last element and remove it from list. self.tmp[:-1] will return last one and still remain it in list


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.