I'm trying to solve a problem using backtracking and I need the permutations of numbers for it. I have this basic algorithm that does it but the problem is... the results don't come in the normal order. def perm(a,k=0): if(k==len(a)): print(a) else: for i in range(k,len(a)): a[k],a = a,a[k] perm(a, k+1) a[k],a = a,a[k] Example: for [1,2,3] the normal results would be: [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] Whereas this algorithm will interchange the last 2 elements. I understand why. I just don't know how to correct this. I don't want to use the permutations from itertools. Can the code above be easily fixed to work properly? What would be the complexity for this algorithm from above? Continue reading...