[leetcode]Generate Parentheses

來源:互聯網
上載者:User

標籤: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  }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.