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.有效的算法来自简单的代码。

  • 相关阅读:
    服务的有状态和无状态
    微服务-服务治理
    微服务-服务注册与发现
    微服务-技术的选型
    微服务的数据一致性
    微服务的服务拆分
    初识微服务
    REST API风格
    算法
    JS 判断PC、android、ios、微信浏览器
  • 原文地址:https://www.cnblogs.com/lichen782/p/leetcode_Generate_Parenthness.html
Copyright © 2011-2022 走看看