zoukankan      html  css  js  c++  java
  • leetcode--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:

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

    public class Solution {
        /**In order to generate valid parenthesis, the number of 
    	 * "(" should not smaller than the number of ")". So, we use a List<Integer>
    	 * to save the number of "(". So the number of ")" can be calculated.
    	 * @param n --Integer, number of parentheses
    	 * @return List of valid parentheses strings
    	 * @author Averill Zheng
    	 * @version 2014-06-04
    	 * @since JDK 1.7
    	 */
        public List<String> generateParenthesis(int n) {
            List<String> validParen = new ArrayList<String>();
    		List<Integer> numberOfLeftParen = new ArrayList<Integer>();
    		if(n > 0){
    			validParen.add("(");
    			numberOfLeftParen.add(1);
    			for(int i = 2; i <= 2*n; ++i){
    				List<String> tempValidParen = new ArrayList<String>();
    				List<Integer> num = new ArrayList<Integer>();
    				int length = validParen.size();
    				for(int j = 0; j < length; ++j){
    					//the length of string in list now is i - 1
    					int leftParen = numberOfLeftParen.get(j); // it implies that number of ")" is i - 1 - leftParen					
    					String s = validParen.get(j);
    					if(leftParen == n){
    						tempValidParen.add(s + ")");
    						num.add(leftParen);
    					}
    					else if(leftParen <= (i - 1 - leftParen)){
    						tempValidParen.add(s + "(");
    						num.add(leftParen + 1);
    					}
    					else{
    						tempValidParen.add(s + "(");
    						num.add(leftParen + 1);
    						tempValidParen.add(s + ")");
    						num.add(leftParen);
    					}
    				}
    				validParen = tempValidParen;
    				numberOfLeftParen = num;
    			}
    		}
    		return validParen;
        }
    }
    

      

  • 相关阅读:
    shell脚本中生成延时
    linux小技巧
    自定义微信圈分享带的图片和内容
    OOM killer
    svn报错
    Fatal error: Call-time pass-by-reference has been removed
    ThinkPHP3.1.3源码分析---php文件压缩zlib.output_compression 和 ob_gzhandler
    确保 PHP 应用程序的安全
    判断来自电脑还是手机
    以About Us为范例在Zen cart中增加页面
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3772537.html
Copyright © 2011-2022 走看看