[Leetcode] Generate Parentheses

3394 단어 LeetCode
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: "((()))", "(()())", "(())()", "()(())", "()()()"
귀속과 심수.
 1 class Solution {

 2 public:

 3     void getRes(vector<string> &res, int st, string str, int count, int n) {

 4         if (str.length() > 2 * n || st > n) return;

 5         if (count == n && st == 0) {

 6             res.push_back(str);

 7             return;

 8         }

 9         getRes(res, st + 1, str + '(', count, n);

10         if (st > 0) getRes(res, st - 1, str + ')', count + 1, n);

11     }

12     

13     vector<string> generateParenthesis(int n) {

14         vector<string> res;

15         getRes(res, 0, "", 0, n);

16         return res;

17     }

18 };

좋은 웹페이지 즐겨찾기