[leetcode]Generate Parentheses

新博文地址:[leetcode]Generate Parentheses

感觉新写的代码可读性稍稍好点(≧▽≦)/~~(≧▽≦)/~

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:

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

 虽然有自己的思路,但是看了这份代码之后深深为这位FB大神折服,我太渣了。。。代码又长又丑效率又低,实在没脸贴出来了,简单把大神的代码敲了一遍,DFS用的这么风骚,膜拜

ArrayList<String> list = new ArrayList<String>();
	private void dfs(int length,int maxDep,int leftToken,int leftTokenCount,String s){
		if(leftTokenCount * 2 > maxDep){//剪枝
			return ;
		}
		if(length == maxDep){
			list.add(s);
			return;
		}
		for(int i = 0; i < 2; i++){
			if(i == 0){
				dfs(length + 1, maxDep, leftToken + 1, leftTokenCount + 1, s + "(");
			}else{
				if(leftToken > 0){
					dfs(length + 1, maxDep, leftToken - 1, leftTokenCount, s + ")");
				}
			}
		}
	}
	
	public ArrayList<String> generateParenthesis(int n) {
		dfs(0, 2*n, 0, 0, "");
		return list;
	}

 

你可能感兴趣的:(LeetCode)