原题链接在这里: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 }