class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
self.res = [];
self.dfs(num, 0)
return self.res
def dfs(self, num, level):
if level == len(num):
self.res.append(num)
print(num)
return
for i in range(level, len(num)):
num[i], num[level] = num[level], num[i]
self.dfs(num, level+1)
num[i], num[level] = num[level], num[i]
The above code is used to generate all permutations given a collection of numbers. For example, num = [1, 3] The result will be: [1 3], [3, 1]
But there is a bug for the above code that I don't understand, which is self.res.append(num).
If I change it to self.res.append(num[:]), then the code is correct. Can anyone explain why?
Using self.res.append(num), the result is:
[1, 3], [1, 3]
Using self.res.append(num[:]), the result is:
[1, 3], [3, 1]