2

Given two numbers n and k and you have to find all possible combination of k numbers from 1…n. I am implementing this using DFS algorithm. But my ans array return None, whereas if I try to print temp the combinations are generated correctly. What am I doing wrong ? In this link from Geeks for Geeks It is working correctly for C++

Here is my code:

def DFSUtil(ans, temp, n, left, k):
    if k == 0:
        ans.append(temp)
        return

    for i in range(left, n+1):
        temp.append(i)
        DFSUtil(ans, temp, n, i+1, k-1)
        temp.pop()


def DFS(n, k):
    ans = []
    temp = []
    DFSUtil(ans, temp, n, 1, k)
    return ans

n = 5
k = 3
ans = DFS(n, k)
for i in range(len(ans)):
    for j in range(len(ans[i])):
        print(ans[i][j], end=' ')
    print()

Expected work:

Input : n = 4 
        k = 2
Output : 1 2 
         1 3 
         1 4 
         2 3 
         2 4 
         3 4
busybear
  • 10,194
  • 1
  • 25
  • 42
ananya
  • 879
  • 1
  • 7
  • 14

2 Answers2

3

You are modifying the temp list which is passed as a reference. You should pass a copy of temp in recursion, e.g.:

DFSUtil(ans, temp.copy(), n, i+1, k-1)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Thank you so much. It worked! But I did it like that since I saw the original code in C++ passed temp as a reference as well so i got confused. Thanks again!! – ananya Jan 07 '19 at 03:10
  • Sorry, not an expert on C++ but check out [this question](https://stackoverflow.com/questions/2275076/is-stdvector-copying-the-objects-with-a-push-back) that might be a hint. – Selcuk Jan 07 '19 at 03:40
1

You need to append a copy of the relevant data, not the mutable list itself like:

Append a copy

if not(ans and ans[-1] == temp[:-1]):
    ans.append(list(temp[:-1]))

Test Code:

def DFSUtil(ans, temp, n, left, k):
    if k == 0:
        if not(ans and ans[-1] == temp[:-1]):
            ans.append(list(temp[:-1]))
        return

    for i in range(left, n + 1):
        temp.append(i)
        DFSUtil(ans, temp, n, i + 1, k - 1)
        temp.pop()


def DFS(n, k):
    ans = []
    temp = []
    DFSUtil(ans, temp, n, 1, k)
    return ans


n = 5
k = 3
ans = DFS(n, k)
for i in range(len(ans)):
    for j in range(len(ans[i])):
        print(ans[i][j], end=' ')
    print()

Results:

1 2 
1 3 
1 4 
2 3 
2 4 
3 4 
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135