标签:for ati ons com write 题目 main 个数 pre
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); } } }
标签:for ati ons com write 题目 main 个数 pre
原文地址:http://www.cnblogs.com/lilei2blog/p/7799586.html