leetcode frame data structure algorithms - backtracking

Backtracking

After backtracking algorithm it is actually a prelude to a N-tree traversal plus preorder traversal of it, but backtracking algorithm is a template, once mastered, can spike related issues. Now, let's step by step to understand.

// 二叉树遍历框架
def traverse(root):
    if root is None: return
    # 前序遍历代码写在这
    traverse(root.left)
    # 中序遍历代码写在这 
    traverse(root.right)
    # 后序遍历代码写在这

// N 叉树遍历框架
def traverse(root):
    if root is None: return
    for child in root.children:
        # 前序遍历代码写在这
        traverse(child)
        # 后序遍历代码写在这

The overall framework of the algorithm

Position backtracking algorithm tree traversal is N, N is equal to the current options available to (choices) the total number, while traversing the front position to the current selection (choose process), and then begins recursively, traversing the final sequence after cancel the current selection (unchoose process). Backtracking template pseudo-code as follows:

"""
choiceList:当前可以进行的选择列表
track:可以理解为决策路径,即已经做出一系列选择
answer:用来储存我们的符合条件决策路径
"""

def backtrack(choiceList, track, answer):
    if track is OK:
        answer.add(track)
    else:
        for choice in choiceList:
            # choose:选择一个 choice 加入 track
            backtrack(choices, track, answer)
            # unchoose:从 track 中撤销上面的选择

Backtracking is equivalent to a decision-making process recursively traverse a decision tree, exhaustive of all decisions and to meet the requirements of the decision singled out.
How to make the computer correctly exhaustive and compare all the decisions, we need a backtracking algorithm design techniques, backtracking algorithm lies in the core logic choose how to design and unchoose section.
DETAILED DESCRIPTION Hereinafter to principles and techniques of backtracking algorithm issue by learning the full array (Permutation) and N Queens

Full array problem

Given a sequence of numbers do not repeat, return to full alignment. Such as input [1,2,3]

Our idea is to first fix the first number is one, then full permutation 2,3; 2 and then fixed to the first number, the whole arrangement 1,3; 3 is then fixed to the first number, the whole arrangement 1 and 2
Here Insert Picture Description
can be found in each level is to go down in "select list" in a pick "select" join "decision path", and then choose delete from the "select list" in (avoid after repeated selection); when a decision Upon completion of exploration branch, we have to back up, take the branch of "selection" was removed from the "decision list", and then this "selection" rejoin "select list" (for other branches of the decision to use).
The above is a template and choose unchoose process, choose to explore the process down, be a choice; unchoose process is back up, just choose the revocation.
This time should be very clear, we can now for the full array of specific questions about backtracking template
Here Insert Picture Description
then write code according to this idea, though not pretty, but it was in line with backtracking algorithms and design patterns can solve the problem:

Here Insert Picture Description

N Queens

The question we should have heard: Queen chess sideways, vertically, diagonally attack; to a chessboard N × N and N Queens, and how to place the Queen, in order to make any two can not attack each other to ?
Here Insert Picture Description
Direct look at the code, you will find the above Java code is exactly the same template:
Here Insert Picture Description

Complexity Analysis

Backtracking algorithm to analyze the time complexity of it. The complexity of such a recursive tree analysis are: Total time = Total time of a recursive tree nodes each recursive × node needs.

Full permutation problem, the number of nodes is equal to n + n * (n-1) + n * (n-2) ... * n !, does not exceed the sum O (n * n!).

Method for the Java code to process each node needs to O (n) time since track.contains (nums [i]) to scan an array of this operation.

So full permutation problem does not exceed the total time O (n ^ 2 * n!).

N Queens, the total number of nodes n + n ^ 2 + n ^ 3 + ... + n ^ n, no more than O (n ^ (n + 1)).

Each processing node in order to avoid the need to scan the board up Queen attack each other, requires O (n) time.

N Queens so the total time of less than O (n ^ (n + 2)).

Visible, backtracking algorithm complexity is extremely high, even higher than exponentially, because the tree is doomed outcome of the complexity of the explosion.

You may ask, before the dynamic programming optimization method in an article is not mentioned specifically optimized time complexity of the tree structure of it? Dimensionality reduction can not blow it?

But here you can not do any optimization. Once again, the computer work strategy is exhaustive. A major feature of Dynamic Programming: overlapping sub-problems, can make the kind of issues "smart exhaustive." But look at backtracking algorithm decision tree, there overlapping sub-problems do not exist, optimization of the question.

Like let you find the largest element in the array, at least you have to traverse the entire array it again, you can re-optimization? impossible.

Published 79 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_34219959/article/details/102649466