• 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) ;
        }
      }
    }

  • 相关阅读:
    多线程(一)高并发和多线程的关系
    spring源码浅析——IOC
    网络爬虫(java)
    数据结构—平衡二叉树
    设计模式—抽象工厂模式
    设计模式—工厂方法模式
    scala(二) Future执行逻辑解读
    java异常处理机制
    为什么覆写equals必须要覆写hashCode?
    Scala对MongoDB的增删改查操作
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8689816.html
Copyright © 2020-2023  润新知