Topic:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Ideas:
The number of all combinations C is a Cattleya number.
Use a smaller c to solve all the possibilities of the combination. Let's see how it's solved. Recursive method is generally used, this can be attributed to sub-problem to solve. The number of opening parentheses is recorded in each recursive function and the number of closing parentheses that can be added, and then each time there are two choices, one is to put the left parenthesis, and the other is put in the closing parenthesis. However, these are conditional, the number of opening parentheses is greater than 0, the number of closing parentheses that can be added is greater than 0 (the result is guaranteed to be legal). The recursive end condition is that the number of left and right brackets is 0.
Attention:
1. Ingenious design, to ensure the legitimacy of the results, you must ensure that the number of left brackets >0 (add opening parenthesis); the number of closing parentheses (number of opening brackets > closing parenthesis) that can be added
<span style= "FONT-SIZE:14PX;" >//iterates through all possibilities based on the number of left brackets remaining and the number of closing parentheses that can be added, as long as they are not zero, two choices (traversing two forks) if (M > 0) {generateparenthesis_helper (ret , str + ")", N, M-1); } if (n > 0) {generateparenthesis_helper (ret, str + "(", n-1, m+1);} </span>
2. To be precise, this problem does not involve backtracking, we just traverse a valid two-fork tree (which conforms to the parentheses) and print all the results. So there is no need to add the result of Pop_back (). Because we are go_deeper with conditions, and legally, there are always two choices.
You can try to draw an n = 2 traversal result to deepen your understanding.
Complexity: O (number of results).
AC Code:
<span style= "FONT-SIZE:14PX;" >class Solution {public: vector<string> generateparenthesis (int n) { vector<string> ret; if (n <= 0) return ret; Generateparenthesis_helper (ret, "", N, 0); return ret; } Private: void Generateparenthesis_helper (vector<string>& ret, string str, int n, int m) { if ( n = = 0 && m = = 0) { ret.push_back (str); return; } Depending on the number of left brackets remaining, and the number of closing parentheses that can be added, it is possible to traverse all possibilities, as long as they are not zero, two times (traversing two forks) if (M > 0) {generateparenthesis_helper (ret, STR + ")", N, M-1); } if (n > 0) {generateparenthesis_helper (ret, str + "(", n-1, m+1);}} ; </span>
[C + +] leetcode:84 Generate Parentheses (Cattleya number)