5

I am working the this problem on 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.

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. The same c++ code works alright:

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
  • 1
    path is passed by reference, so you are always only manipulating the same instance. pass path[:] to pass a copy that you can modify Commented Sep 14, 2016 at 0:33

1 Answer 1

12

The problem is here:

solutions.append(path)

in C++, vector::push_back makes a copy of path (internally). But in Python, everything is a reference. So you build up your solutions as a list of many references to the same path, which eventually gets reduced to nothing.

You want a copy:

solutions.append(list(path))

or:

solutions.append(path[:])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.