python递归通过引用或值传递?

时间:2016-09-14 00:24:02

标签: python c++ recursion subset

我正在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]]

我有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)

输出现在是:     [[],[],[],[],[],[],[],[]]

似乎是Python传递引用/传递值导致问题,但我无法弄清楚如何。相同的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);
}
};

1 个答案:

答案 0 :(得分:4)

问题在于:

solutions.append(path)

在C ++中,vector::push_back复制path(内部)。但在Python中,一切都是参考。因此,您将solutions建立为对同一path的许多引用的列表,最终会减少为零。

你想要一份副本:

solutions.append(list(path))

或:

solutions.append(path[:])