Backtracking Algorithm of Algorithm Design Method

backtracking algorithm

introduce

Backtracking algorithm is a method in algorithm design. Backtracking is a strategy for incrementally finding and constructing solutions to problems. Backtracking algorithms start with one possible action to solve the problem, and if not, backtrack and choose another action until the problem is solved.

It's like you encounter three forks in a maze. After you choose the first one, you find that the road does not work. Do you want to go back to the original point and choose the second road, and so on, and finally choose the correct one.

What problems are suitable for backtracking algorithms?

  • There are many forks
  • There's a dead end in these roads, and there's a way out
  • Usually need to use recursion to simulate all paths

base case

scene one

full array

// 输入
const input = [1, 2, 3]

// 输出
const output = [
    [1, 2, 3],
    [1, 3, 2],
    [2, 1, 3],
    [2, 3, 1],
    [3, 1, 2],
    [3, 2, 1]
]

step:

  1. Simulate all exit cases with recursion
  2. When encountering a situation that contains repeated elements, backtrack
  3. Collect all cases that reach the end of the recursion and return

Original Link: Vegetable Garden Front End

Guess you like

Origin blog.csdn.net/qq2603375880/article/details/131813155