This must be a classic interview question, however, I'm having a problem understanding it.
Below is my implementation in Python and if you run it, it's only printing ab, ac, ad. It doesn't go to the 'b' (bc, bd) level.
def Print_nCk (the_list, k, str_builder, used):
if len(str_builder) == k:
print str_builder
return
else:
for i in xrange(len(the_list)):
if used[i] !=True:
str_builder+=the_list[i]
used[i] = True
Print_nCk(the_list, k, str_builder, used)
str_builder = str_builder[:-1]
Print_nCk(['a','b','c','d'], 2, "",[False,False,False,False])
The right answer is ab,ac,ad,bc,bd,cd when above line is passed.
I know the right implementation from here without using used param (http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/) but
my question is what is wrong is my implementation?
Can you shed some light on it?
To debug, I printed out "used" every time. The used param becomes (True, True, True, True) after printing "ad" then it doesn't go deeper than that. What's the smart way to fix the used, if I insist on using used?
>>> [''.join(c) for c in combinations(['a','b','c','d'], 2)] ; ['ab', 'ac', 'ad', 'bc', 'bd', 'cd']