[問題] append(element+[])
大家好
最近在刷leetcode 寫到一題給出一組數列 求所有permutations的可能
https://leetcode.com/problems/permutations/description/
我的code是這樣的,主體無窮遞迴的方式求解
class Solution:
def getSolution(self, x):
cach = []
result = []
self.permutations(x, cach, result)
return result
def permutations(self, x, cach, result):
if len(x) == 0:
result.append(cach)
for i in range(len(x)):
cach.append(x[i])
self.permutations(x[:i]+x[i+1:], cach, result)
cach.pop()
但我發現在上色部分append完的result在下一次append前他的值都會自動被改變
而我google了使用一樣解法的code,發現只要將append(cach)改成append(cach+[])
這樣的輸出就不會有值被改變的問題
我查了半天找不到類似的解釋 不太知道+[]的用意是什麼
所以來這邊請教大家
先謝謝大家的回答了!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 72.229.255.136
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1530758013.A.931.html
→
07/05 10:41,
7年前
, 1F
07/05 10:41, 1F
→
07/05 10:41,
7年前
, 2F
07/05 10:41, 2F
→
07/05 10:51,
7年前
, 3F
07/05 10:51, 3F
→
07/05 10:51,
7年前
, 4F
07/05 10:51, 4F
推
07/05 11:23,
7年前
, 5F
07/05 11:23, 5F
→
07/05 11:24,
7年前
, 6F
07/05 11:24, 6F
→
07/05 12:31,
7年前
, 7F
07/05 12:31, 7F
→
07/05 12:52,
7年前
, 8F
07/05 12:52, 8F
推
07/05 23:02,
7年前
, 9F
07/05 23:02, 9F
→
07/05 23:02,
7年前
, 10F
07/05 23:02, 10F
Python 近期熱門文章
PTT數位生活區 即時熱門文章