zoukankan      html  css  js  c++  java
  • 22. 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应该写什么。其实就是把dfs代入不同的数值,再写一遍就行了。不同条件的可以分开写

    dfs字符串的题目,一般有个String currentString。这里要判断左右开口数,还要加open close变量

    class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> results = new ArrayList<>();
            
            //cc
            if (n < 0) return results;
            
            //dfs
            dfs(n, 0, 0, "", results);
                
            //return
            return results;
        }
        
        public void dfs(int n, int open, int close, String cur, List<String> results) {
           //exit
            if (cur.length() >= 2 * n) {
                results.add(cur);
                return ;
            }
            
            if (open < n)
                dfs(n, open + 1, close, cur + '(', results);
            if (close < open)
                dfs(n, open, close + 1, cur + ')', results);
        }
    }
    View Code
    
    
    


  • 相关阅读:
    analysis of algorithms
    Measurement of Reflected Radiation
    lecture 5
    lecture 3
    字符串
    Emission of Radiation辐射发射
    Electromagnetic Radiation(EMR) 电磁辐射
    Linux FTP服务器-VSFTPD虚拟用户配置
    jenkins notes
    python nose使用记录
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13388355.html
Copyright © 2011-2022 走看看