Generate Parentheses
生活随笔
收集整理的這篇文章主要介紹了
Generate Parentheses
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
描述
Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路
該題目有一個(gè)規(guī)則是左括號(hào)個(gè)數(shù)得小于右括號(hào)個(gè)數(shù),根據(jù)這個(gè)規(guī)則,可用通過動(dòng)態(tài)規(guī)劃來解決這個(gè)題目
代碼
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);}}}
轉(zhuǎn)載于:https://www.cnblogs.com/lilei2blog/p/7799586.html
總結(jié)
以上是生活随笔為你收集整理的Generate Parentheses的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LInux下装jdk
- 下一篇: 第十次ScrumMeeting博客