I am facing a confusing python problem when generating all lists summed to a number with a fixed length using DFS.
The problem is that local results (temp
variable) cannot be stored in a global list (res
). When I print res
with print(res, y)
, there are numbers of lists in the res
, however, there is none using return res
in the last line (attached figure).
class Solution:
def connect(self , m , n ):
res = []
def helper(x, y, res, temp):
if len(temp) == y:
temp.sort()
print(temp, y)
res.append(temp) #+= [temp]
print(res, y)
return
if x >= 0:
for i in range(0, x+1):
temp.append(i)
helper(x - i, y, res, temp)
temp.pop()
temp = []
helper(m, n, res, temp)
return res #len([i for i in res if sum(i) == m])
Solution().connect(5, 3)