我有兩個代碼示例,它們的作業原理相同:
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
m = len(nums)
ans = []
def solve(lst, tmp):
if len(tmp) == m:
ans.append(tmp)
for i in range(len(lst)):
solve(lst[:i] lst[i 1:], tmp [lst[i]])
solve(nums, [])
return ans
還有這個:
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ans = []
l = len(nums)
def solve(tmp, c):
""" why should I use tmp[:] here? instead of tmp?"""
if len(tmp) == l:
ans.append(tmp[:])
for i in c:
if c[i] > 0:
tmp.append(i)
c[i] -= 1
solve(tmp, c)
c[i] = 1
tmp.pop()
solve([], Counter(nums))
return ans
對于我突出顯示的行,如果我將其從 更改tmp[:]為tmp,那么它將是一個空串列串列?
我想知道什么時候應該附加串列的副本,什么時候應該只附加 tmpo 串列?
uj5u.com熱心網友回復:
當你這樣做時tmp.append(i),你隱式地修改了該串列的參考,該串列將存盤在ans. 當你復制時,這不會發生
對于第一個答案,添加是回傳一個新串列,而不是直接附加到 tmp
要獲得類似的行為,您必須這樣做
tmp = [lst[i]]
solve(lst[:i] lst[i 1:], tmp)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/415098.html
標籤:
下一篇:如何附加不同長度的串列串列
