LeetCode 22. Generate Parentheses

原题链接在这里:https://leetcode.com/problems/generate-parentheses/

题目:

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

题解:

DFS state needs current ( count, current ) count, current string and res.

When l==n && r==n, add cur to res and return.

If l>n or r>n, return. 

If r>l, it means there current has more ) than (, which is illegal, return.

否则先加左括号,再加右括号.

Time Complexity: exponential.

Space: O(n) 一共用了O(n)层stack.

AC Java:

 1 class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> res = new ArrayList<String>();
 4         if(n < 1){
 5             return res;
 6         }
 7         
 8         dfs(n, 0, 0, "", res);
 9         return res;
10     }
11     
12     private void dfs(int n, int l, int r, String cur, List<String> res){
13         if(l==n && r==n){
14             res.add(cur);
15             return;
16         }
17         
18         if(l>n || r>n || r>l){
19             return;
20         }
21     
22         dfs(n, l+1, r, cur+'(', res);
23         dfs(n, l, r+1, cur+')', res);
24     }
25 }

AC Python:

 1 class Solution:
 2     def generateParenthesis(self, n: int) -> List[str]:
 3         res = []
 4         self.dfs(n, 0, 0, "", res)
 5         return res
 6     
 7     def dfs(self, n: int, l: int, r: int, item: str, res: List[str]) -> None:
 8         if l == n and r == n:
 9             res.append(item)
10             return
11         
12         if l > n or r > n or r > l:
13             return
14         
15         self.dfs(n, l + 1, r, item + "(", res)
16         self.dfs(n, l, r + 1, item + ")", res)

Unique Binary Search Trees II类似。

posted @ 2015-09-21 07:15  Dylan_Java_NYC  阅读(242)  评论(0编辑  收藏  举报