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