• 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);
    		}
    	}
    
    }
    

      

  • 相关阅读:
    网络配置
    数据管理
    仓库
    dockerfile
    docker 概念
    查看日志小技巧
    springboot缓存
    360笔试算法题 AT变换
    删除链表里全部重复元素以及删除链表重复元素只保留一个
    报错类型
  • 原文地址:https://www.cnblogs.com/lilei2blog/p/7799586.html
Copyright © 2020-2023  润新知