zoukankan      html  css  js  c++  java
  • LeetCode 笔记系列五 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:

    "((()))", "(()())", "(())()", "()(())", "()()()"

    解法:leetcode上的解法很赞。 其实这也是利用的递归的分支。构建了一树状结构并遍历,叶子节点就是valid的结果。

     1 public static ArrayList<String> generateParenthesis(int n) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         ArrayList<String> result = new ArrayList<String>();
     5         generate(result, "",0,0,n);
     6         return result;
     7     }
     8     
     9     private static void generate(ArrayList<String> result, String prefix, int leftCount, int rightCount,int totalPairs){
    10         if(leftCount == totalPairs){
    11             for(int i = 0; i < totalPairs - rightCount;i++){
    12                 prefix += ")";
    13             }
    14             result.add(prefix);
    15             return;
    16         }
    17         generate(result, prefix + "(", leftCount + 1, rightCount, totalPairs);
    18         if(leftCount > rightCount) generate(result, prefix +")", leftCount, rightCount + 1,totalPairs);
    19     }
    View Code

    leftCount和rightCount分别记录当前高度(或者长度)中,“(“和“)”的数目。如果leftCount等于了总共要求的括号对数,我们就把剩余的右括号添加进去并作为一个结果记录下来。这个有一些类似二叉树的post order遍历。

    值得学习的地方:

    1.利用递归模拟组合操作,做有序搜索;

    2.有效的算法来自简单的代码。

  • 相关阅读:
    CF1375 题解
    CF1381 题解
    CF1394 题解
    CF1383 题解
    git pull提示You are not currently on a branch. Please specify which
    centos6 YUMREPO ERROR ALL MIRROR URLS ARE NOT USING FTP, HTTP[S] OR FILE
    git报错fatal protocol error bad pack header
    Mongo服务器管理之部署MongoDB讨论
    Mongo服务器管理之备份
    Mongo服务器管理之监控MongoDB
  • 原文地址:https://www.cnblogs.com/lichen782/p/leetcode_Generate_Parenthness.html
Copyright © 2011-2022 走看看