[英]python recursion pass by reference or by value?
I am working the this problem on leetcode: 我正在leetcode上解决此问题:
Given a set of distinct integers, nums, return all possible subsets.
input =[1,2,3]
output =[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
I have the c++ solution, which is accepted, and then i coded exactly the same python solution. 我有被接受的c ++解决方案,然后我编写了完全相同的python解决方案。
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
solutions = []
self._get_subset(nums, 0, [], solutions)
return solutions
@staticmethod
def _get_subset(nums, curr, path, solutions):
if curr>= len(nums):
solutions.append(path)
return
path.append(nums[curr])
Solution._get_subset(nums, curr+1, path, solutions)
path.pop()
Solution._get_subset(nums, curr+1, path, solutions)
The output is now: [[],[],[],[],[],[],[],[]] 现在的输出为:[[],[],[],[],[],[],[],[]]
It seems it is the Python pass by reference/ pass by value causing the problem, but i can't figure out how. 看来这是Python按引用传递/按值传递引起的问题,但我不知道如何。 The same c++ code works alright:
相同的c ++代码可以正常工作:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> solutions;
vector<int> path;
_get_path(nums, 0, path, solutions);
return solutions;
}
void _get_path(vector<int>& nums,
int curr,
vector<int>& path,
vector< vector<int> > &solutions)
{
if(curr >= nums.size()){
solutions.push_back(path);
return;
}
path.push_back(nums[curr]);
_get_path(nums, curr+1, path, solutions);
path.pop_back();
_get_path(nums, curr+1, path, solutions);
}
};
The problem is here: 问题在这里:
solutions.append(path)
in C++, vector::push_back
makes a copy of path
(internally). 在C ++中,
vector::push_back
(内部)复制path
。 But in Python, everything is a reference. 但是在Python中,一切都是参考。 So you build up your
solutions
as a list of many references to the same path
, which eventually gets reduced to nothing. 因此,您将
solutions
构建为包含对同一path
的许多引用的列表,最终将其简化为零。
You want a copy: 您想要一份副本:
solutions.append(list(path))
or: 要么:
solutions.append(path[:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.