leetcode 22 questions: brackets generation

Force wear the title can be roughly divided into the following categories:

  • Thorough analysis of some complex rules, is likely to construct a state machine, fully consider the boundary conditions.

  • Application of certain data structures and algorithms.

  • Comprehensive application of mathematical concepts, traverse, dynamic programming, etc.

By analysis, this question should belong 1,2 binding.

 Thinking: generating a first {-> each produce two cases ({or}) ->} {does not produce a number less than the number -> {} is equal to the number 2N at the end

Backtracking

Backtracking is also called heuristics, it is a systematic method for solving search problems.

Backtracking is particularly effective in solving multiple choice questions, the general idea is as follows: In the current scenario, there are several options to operate, there may be two results: first, breach of the appropriate conditions, can only return (back), another this is actually the last election to choose the right and ends. Therefore, there are three elements at the back, can be summed up in three elements of this problem will be resolved quickly:

1 found Select

Constraints 2, i.e., selecting operation carried out only under conditions

3 End

In this problem:

1 Selection:

Bracketed

2 Constraints:

(1) If the left parenthesis not complete addition of the left bracket

(2) if the right parenthesis is less than the left parenthesis, right parenthesis plus

3 End:

Parentheses around the addition was complete (length = 2n) End

IF (left and right brackets have been exhausted) { 
  added to Solution Set return 
}
 // else begin again options
 IF (there may be a left parenthesis) { 
  add a left parenthesis, recursively 
} 
IF (less than a right parenthesis left parenthesis) { 
  add a right parenthesis, recursively 
}
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []
        def backtracking(s="",left=0,right=0):
            if len(s)==2*n:
                res.append(s)
                return
            if left<n:
                backtracking(s+'(',left+1,right)
            if right<left:
                backtracking(s+')',left,right+1)
        backtracking()
        return res

 

Guess you like

Origin www.cnblogs.com/cchenyang/p/11418313.html