Skip to content
Advertisement

Subset algorithm behaves differently in Python than C++

The algorithm follows recursive approach, dividing the array in two parts:

  1. In first recursion the first part is neglected
  2. In second part the first part is added

Code for C++ (Works Fine)

JavaScript

Code for Python

JavaScript

Advertisement

Answer

In the C++ version, res is a by-value parameter, so a copy of the vector is made in each call. Python passes references to the list, so you keep modifying the same temp list throughout the algorithm. Pass a copy when you make the recursive calls.

There’s also no need for an empty nested list in the initial value of self.result. The C++ version starts with an empty vector.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement