### AlRntn's blog

By AlRntn, history, 3 weeks ago,

Backtracking: This algorithm helps you solve problems in a specific way using your skills in recursive programming. It comes in handy whenever you have a set of valid answers to a problem and need to search through them all or construct a suitable answer, this algorithm is a general algorithm for finding all or some solutions in some computational problems. The backtracking method is an algorithmic method to solve some kind of problems in which we need to build and examine all possible situations or a number of good situations of an arrangement(combination), in this algorithm all possible situations are created , and after examining each one, if it is approved based on the request of the problem we will accept it as a answer(kind of like brute force we find each possible combination). Note that this method is useful when we cant use a faster algorithm(like: Greedy or Dp).

the General Backtracking Method is like this(pseudocode):

solve(X):
if X is accepted:
exit
while we can change X:
change X
if X is valid:
solve(X)
undo last change from X


The base of the algorithm is in 4 parts: the condition of finding the answer (lines 1 to 3) — finding all the different states of the answer (lines 4 to 6) — recursive call (line 7) — return the last change made (line 8).

Some Backtracking Problems:

1-Print all strings of length n that are made only of letters a, b, and c.