22. 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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
class Solution { public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList<>(); if( n == 0){ return ans; } StringBuilder current = new StringBuilder(); dfs( ans, n, current, 0, n, n); return ans; } private void dfs(List<String> ans, int n, StringBuilder current, int index, int left, int right){ if(index == n * 2 ){ ans.add(current.toString()); ///// sb.toString() return; } // pick '(' if( left > 0 ){ current.append('('); dfs(ans, n, current, index + 1, left - 1, right); current.deleteCharAt(current.length() - 1); } if(right > 0 && left <= right - 1){ current.append(')'); dfs(ans, n, current, index+1, left, right - 1); current.deleteCharAt(current.length() - 1); } } }
() three pairs
6 levels
every level, add '(' or ')'
( or )
( or )
( or )
( or )
( or )
( or )
only add '(' when there is enough '(' left , and only add ')' when we used more '(' than ')' and there is enough ')' left
do this condition check before adding any parentheses . if satisfies the condition, add the parenthese and dfs on it, and don't forget backtracking on the stringbuilder
time complexity 2 ^ ( pairs * 2)
api :
current is a stringbuilder
current.deleteCharAt(current.length() - 1);
posted on 2018-07-18 07:48 猪猪🐷 阅读(112) 评论(0) 收藏 举报
浙公网安备 33010602011771号