博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LF.66.All Valid Permutations Of Parentheses I
阅读量:6245 次
发布时间:2019-06-22

本文共 1579 字,大约阅读时间需要 5 分钟。

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
validParentheses(int n) { // Write your solution here. //assume n>=0 List
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
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) ; } }}

 

 

 

转载于:https://www.cnblogs.com/davidnyc/p/8689816.html

你可能感兴趣的文章
互联网分布式微服务云平台规划分析--平台整体规划
查看>>
Swift对象转为C指针
查看>>
Spring Cloud构建微服务架构:服务容错保护(Hystrix服务降级)
查看>>
ThinkSNS系统升级,版本多样化
查看>>
ecshop使用smtp发送邮件
查看>>
RubyInstaller
查看>>
21. SQL -- TSQL架构,系统数据库,文件,SQL 认证,TSQL语句
查看>>
CentOS6.0添加163和epel源
查看>>
使用组策略与脚本发布Office 2010
查看>>
Open××× 分配固定IP
查看>>
elk+redis centos6.6安装与配置
查看>>
linux下svn命令大全
查看>>
windows server 2008 在vm上安装
查看>>
我的友情链接
查看>>
谷果等手机刷机build.prop解析
查看>>
Vbox虚拟机下 Linux网络配置
查看>>
Vmware vsphere知识中易混淆和忽略的多个概念
查看>>
Android客户端和服务端如何使用Token和Session
查看>>
Python Pycharm导入第三方包
查看>>
Nginx源码安装
查看>>