algorithm - Python backtracking strings lenght n from alphabet {a,b,c} with #a=#b -


I want to create an algorithm that searches for given n, which is the alphabet {a, b, c} which 'A' number 'B' appears at the same time I

  n = 3 # length string H = -1 # Lamp prefix L = ['A', 'b', ' C '] #alphabet S = [' ',' ',' ',']] #solution par = 0 # This is zero if a and b is the same condition def p (n, h, par, l, s) : If h == n: if equal == 0: print (s) other: in L in i: if i == 'a': par + = 1 if i == 'b' sir '= 1 s [h + 1] = I P (N, H + 1, PAR, L, S) # Repeat After updating the stack if s [h + 1] == 'a': para- = 1 if s [h + 1] == 'b': para + = 1 p (n, h, par, l, s )  

I apologize for poor string implementation but it works and it is only for studying purpose, the question is: what are the ways to avoid some work for algorithms Are you Since it only produces all the N-length strings for this alphabet, then checks for # a and #b at the end. My goal is to get o (n * (the number of strings to print))

You cut If possible, change the following work and do the job:

  If I == 'a': par + = 1 if I == 'b': par- = 1  

  Purabapara = par if i == 'a': par + = 1 if i == 'b': par- = 1 # nh-1 characters dropped in place # And we need to keep at least ABS (equal) characters to reach the stomach (0) if abs (equal to)> Nh-1: continue par = oldpar  

Comments