zoukankan      html  css  js  c++  java
  • LF.66.All Valid Permutations Of Parentheses I

    same as LC.22. Generate Parentheses
    https://leetcode.com/problems/generate-parentheses/description/

    Given N pairs of parentheses “()”, return a list with all the valid permutations.

    Assumptions

    N >= 0
    Examples

    N = 1, all valid permutations are ["()"]
    N = 3, all valid permutations are ["((()))", "(()())", "(())()", "()(())", "()()()"]
    N = 0, all valid permutations are [""]

    public class Solution {
      public List<String> validParentheses(int n) {
        // Write your solution here.
        //assume n>=0
        List<String> res = new ArrayList<>() ;
        StringBuilder sol = new StringBuilder() ;
        dfs(n, res, 0, 0, sol) ;
        return res ;
      }
    
     /*
        n stores total number of "pair of ()" need to add.
        So total levels == 2*n
        1 stores the number of left parenthesis "(" added so far
        r stores the number of right parenthesis ")" added so far
        sol: solution so far
     */
      private void dfs(int n, List<String> res, int l , int r , StringBuilder sol){
         //base case: reach the leaf and its valid value, go back
        if (n == l && l == r ) {
            //always deep copy, be very careful
            res.add(sol.toString());
            return ;
        }
        //case 1: add ( on this level :
        //think n as the length of array, l as index
        if (n > l) {
            dfs(n, res, l+1 , r , sol.append("(")) ;
            //remove
            sol.deleteCharAt(sol.length()-1) ;
        }
        //case 2: add )
        if (n > r && l > r ) {
            dfs(n, res, l, r+1, sol.append(")")) ;
            //remove
            sol.deleteCharAt(sol.length()-1) ;
        }
      }
    }

  • 相关阅读:
    浏览器20年图说简史
    CF1437D Solution
    CF1446B Solution
    CF1444A Solution
    CF1437C Solution
    让您的网站拥有MSDN资源库搜索功能[转摘MSDN]
    自定义web part版面变形的原因
    SPS中模板保存数据库的位置
    利用配置文件自定义站点
    VS.NET2003 开发环境 生成样式表 和 自动书写HTML对象模型
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8689816.html
Copyright © 2011-2022 走看看