Leetcode OJ 22 Generate Parentheses [Medium]
题目描述:
Given n pairs of parentheses, write a function togenerate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
题目理解:
实现一个函数:给定一个整数n,输出所有n对括号的组合。
测试用例:
功能测试:输入1、2、3等;
边界测试:输入0;
性能测试:输入大整数如1000;
分析:
1. 在一个排列中(字符串),每一个位置往前,左括号数leftNum大于等于右括号数rightNum;左括号数号数小于等于n;
2. 可用动态规划(递归)解决该问题:初始leftNum和rightLeft都是0。
3. 对于每一个排列(字符串),字符串初始是空,如果字符串长度等于2n,则将该字符串输出;
4. 如果leftNum小于n,则可向字符串中添加‘(’,leftNum加1,继续进行后续添加括号操作,操作相同;
5. 如果rightNum小于leftNum,则可向字符串中添加‘)’,rightNum加1,继续进行后续添加括号操作,操作相同;
6. 注意4、5步进行时,保证leftNum、rightNum、字符串s都没有被修改;
也就是说,正确的是:
if(leftNum < n){ addParenthesis(result,s+"(",leftNum+1, rightNum,n); } if(rightNum < leftNum){ addParenthesis(result,s+")",leftNum,rightNum+1,n); }
错误的是:
if(leftNum < n){ s += "("; leftNum += 1; addParenthesis(result,s,leftNum, rightNum,n); } if(rightNum < leftNum){ addParenthesis(result,s+")",leftNum,rightNum+1,n); }
解答:
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/8/30.
*/
public class generateParenthesis22 {
public static void main(String[] args) {
int n = 10;
List<String> result = new ArrayList<String>();
addParenthesis(result,"",0,0,n);
System.out.println(result);
}
public static void addParenthesis(List<String> result, String s, int leftNum, int rightNum, int n) {
if(s.length() == 2 * n){
result.add(s);
return;
}
if(leftNum < n){
addParenthesis(result,s+"(",leftNum+1, rightNum,n);
}
if(rightNum < leftNum){
addParenthesis(result,s+")",leftNum,rightNum+1,n);
}
}
}