leetcode小白刷题之旅----22. Generate Parentheses

仅供自己学习

 

题目:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:

Input: n = 1
Output: ["()"]

Constraints:

1 <= n <= 8

 

思路:

回朔法遍历所有可能。一般来说要遍历所有可能 两种情况进行递归即可。因为()是配对的,可以通过计数剩余的(和)数量来保证不会出现不配对的情况,错误情况即(剩余量大于)导致不配对。当()剩余数量都为0后将其存入结果并返回。如果还有剩余(或)将继续递归。

 

代码:

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector <string> res;
 5         int left=n,right=n;
 6         backtracking(left,right,"",res);
 7         return res;
 8     }
 9     void backtracking(int left,int right,string out,vector<string>& res){
10         if(left>right) return;
11         if(left ==0&&right ==0) {res.push_back(out);return;}
12         else{
13             if(left>0) backtracking(left-1,right,out+'(',res);
14             if(right>0) backtracking(left,right-1,out+')',res);
15         }
16     }
17 };

 

posted @ 2021-01-28 11:33  Mrsdwang  阅读(53)  评论(0)    收藏  举报