zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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:

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

    思路:

    对于n个"("和n个")",在递归时保证"("的个数大于")"的个数

    package recursion;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class GenerateParentheses {
    
        public List<String> generateParenthesis(int n) {
            List<String> res = new ArrayList<String>();
            generate(res, n, n, "");
            return res;
        }
        
        private void generate(List<String> res, int left, int right, String s) {
            if (left == 0 && right == 0) {
                res.add(s);
                return;
            }
            
            if (left > 0) 
                generate(res, left - 1, right, s + "(");
            
            if (right > 0 && right > left) 
                generate(res, left, right - 1, s + ")");        
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            GenerateParentheses g = new GenerateParentheses();
            for (String s : g.generateParenthesis(3)) {
                System.out.println(s);
            }
        }
    
    }
  • 相关阅读:
    Struts2文件上传和下载
    Struts2自定义类型转换器
    struts2数据处理的几种方式
    Struts2常量_Action配置路径_通配符
    Struts框架
    struts入门
    Log4J日志组件
    处理文件上传与下载
    文件上传
    国际化和本地化
  • 原文地址:https://www.cnblogs.com/null00/p/5060562.html
Copyright © 2011-2022 走看看