I am learning backtracking algorithms and I have written a program of subset sums. Here's the program:
items = range(1, 10)
result = []
def backtracking(array, target, temparray= []):
if target == 0:
result.append(temparray)
return
for index, item in enumerate(array):
if item > target:
return
temparray.append(item)
backtracking(array[index+1:], target - item, temparray[:])
temparray.pop()
return
backtracking(items, 8)
[print(arr) for arr in result]
That is to get a sum of 8 from the values of 1 to 9 (No repetition), we get this output:-
[1, 2, 5]
[1, 3, 4]
[1, 7]
[2, 6]
[3, 5]
[8]
The output is well and good but when I do same for any number above 50, it keeps on running like forever. I waited almost an hour and still couldn't get the result so I Had to terminate the programme abruptly. Same has been my experience with other backtracking
problems when the values tend to get close to 40-50. Seems like backtracking
is inherently very slow as it involves recursion
and lots of function calls
.
I want to ask if there is anything to speed things in general while implementing backtracking algorithms
. Is there any other more efficient algorithms
to be used in its place. Memoization
doesn't work as list as arguments are not hashable.
I have devised some cool solutions to some of the Project Euler questions but am unable to get an answer for larger values. I know my algorithm is correct but is very slow. Please help.