標籤:style blog http color os for
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,對每一位,嘗試尾碼‘(’ 或 ‘)’,用k記錄左括弧的個數,用couple記錄成功匹配對數,注意剪枝
這個代碼是我看到的幾乎最簡練的演算法:[leetcode]Generate Parentheses
代碼如下:
1 public class Solution { 2 List<String> result = new ArrayList<String>(); 3 public List<String> generateParenthesis(int n) { 4 dfs(new StringBuilder(),0,0,n); 5 return result; 6 } 7 private void dfs(StringBuilder sb,int k,int couple,int n){ 8 if(k == 0 && couple == n && sb.length() == 2 * n ){ 9 result.add(sb.toString());10 return;11 }12 if( k < 0 || sb.length() > 2 * n) return;//剪枝13 char[] c = {‘(‘,‘)‘};14 for(int i = 0; i < 2; i++){15 k = (i == 0 )? k + 1 : k-1;16 if(k > 0 && i == 1) {//配對的前提是k>0,即存在未配對的左括弧17 couple++;18 k--;19 }20 if(k < 0){//如果前面木有左括弧,則只能匹配右括弧21 k++;22 continue;23 }24 dfs(sb.append(c[i]), k,couple, n);25 sb.deleteCharAt(sb.length() - 1);26 }27 }28 }