• Generate Parentheses


    描述

    Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses.
    For example, given n = 3, a solution set is:
    "((()))", "(()())", "(())()", "()(())", "()()()"

    思路

    该题目有一个规则是左括号个数得小于右括号个数,根据这个规则,可用通过动态规划来解决这个题目

    代码

    package com.lilei.myes.es.pack1107;
    
    public class generate_parentheses {
    
    	public static void main(String[] args) {
    
    		int num = 4;
    
    		genp("", num, num);
    	}
    
    	public static void genp(String s, int left, int right) {
    		if (left > 0 && right > 0) {
    
    			if (left == right) {
    				genp(s + "(", left - 1, right);
    
    			} else if (left < right) {
    				genp(s + "(", left - 1, right);
    				genp(s + ")", left, right - 1);
    			}
    
    		} else {
    			for (int i = 0; i < right; i++)
    				s = s + ")";
    			System.out.println(s);
    		}
    	}
    
    }
    

      

  • 相关阅读:
    sort排序
    js数组
    json数据格式 与 for in
    js 定时器
    鼠标滚轮事件
    cookie
    POJ 2387 Til the Cows Come Home
    POJ 1459 Power Network
    HDU 5389 Zero Escape
    HDU 5387 Clock
  • 原文地址:https://www.cnblogs.com/lilei2blog/p/7799586.html
Copyright © 2020-2023  润新知