LeetCode - Generate Parentheses
                                            
 6586 단어  LeetCode
                    
2013.12.7 00:49
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:
"((()))", "(()())", "(())()", "()(())", "()()()"  Solution:
If you're familiar with the Catalan Numbers , you'll see it's a typical solution for this problem.
Since all the combinations are required, we'll use DFS to go through every possible sequence.
Let's consider the recursion in the following way:
1. For a sequence of length 2 * n, there're n '(' and n ')'
2. For a valid sequence, number of '(' will never be less than the number of ')' at any position. If there're more ')' than '(', there must be a mismatch.
3. Always do the recursion from left to right.
Time complexity is H(n) * O(n) = C(2 * n, n)/(n + 1) * n, that's roughly O(n!). Space complexity is not sure yet...
Accepted code:
 1 // 1AC, simple recursion will do, but keep your mind clear or it's easy to get things complicated
 2 class Solution {
 3 public:
 4     vector<string> generateParenthesis(int n) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         result.clear();
 8         
 9         dfs(n, n, "");
10         
11         return result;
12     }
13 private:
14     vector<string> result;
15     
16     void dfs(int cl, int cr, string pat) {
17         if(cl == 0 && cr == 0){
18             result.push_back(pat);
19         }
20         
21         int i;
22         if(cl < cr){
23             if(cl > 0){
24                 dfs(cl - 1, cr, pat + "(");
25             }
26             if(cr > 0){
27                 dfs(cl, cr - 1, pat + ")");
28             }
29         }else if(cl == cr){
30             if(cl > 0){
31                 dfs(cl - 1, cr, pat + "(");
32             }
33         }else{
34             return;
35         }
36     }
37 };이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.