首页 > 其他 > 详细

[LeetCode 22] Generate Parentheses

时间:2015-03-28 08:49:37      阅读:457      评论:0      收藏:0      [点我收藏+]

题目链接:generate-parentheses


import java.util.ArrayList;
import java.util.List;

/**
 * 
		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:
		
		"((()))", "(()())", "(())()", "()(())", "()()()"
 *
 */

public class GenerateParentheses {
	
//	8 / 8 test cases passed.
//	Status: Accepted
//	Runtime: 213 ms
//	Submitted: 0 minutes ago
	
//	时间复杂度O(2^n) 空间复杂度 O(1)
	public List<String> parenthesis = new ArrayList<String>();
   
	public List<String> generateParenthesis(int n) {
        generateParenthesis(n, n, "");
    	return parenthesis;
    }
	// left 表示剩余"("数量, right表示剩余")"数量
	public void generateParenthesis(int left, int right, String s) {
    	if(left == 0) {
    		while(right != 0) {
    			s += ")";
    			right --;
    		}
    		parenthesis.add(s);
    		return;
    	}
    	
    	//选中"("
    	generateParenthesis(left - 1, right, s + "(");
    	
    	//当剩余 ")" 数大于 "(" 数时,选中 ")"
    	if(right > left) {
    		generateParenthesis(left, right - 1, s + ")");
    	}
    }
	public static void main(String[] args) {
//		System.out.println(Arrays.toString(generateParenthesis(0).toArray()));
	}

}


[LeetCode 22] Generate Parentheses

原文:http://blog.csdn.net/ever223/article/details/44687843

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!