leetcode刷题笔记
leetcode22
问题描述:Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.For example, given n = 3, a solution set is:[ "((()))","(()())", "(())()", "()(())", "()()()"]
问题分析
该问题是要求输出括号串的数目,本身括号是一种对称结构,所以可以采取回溯的方式来解决,依次输出左右括号,从而保证括号的对称,这里利用了深度优先遍历的思想。具体代码如下:
public static List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
String sub = "";
generateParenthesisOneByOne(sub,result,n,n);
return result;
}
public static void generateParenthesisOneByOne(String sublist,List<String> list,int left,int right){
if (left > right)
return;
if (left>0){
generateParenthesisOneByOne(sublist+"(",list,left-1,right);
}
if (right>0){
generateParenthesisOneByOne(sublist+")",list,left,right-1);
}
if (left == 0 && right == 0)
{
list.add(sublist);
return;
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<String> re = generateParenthesis(n);
for (int i=0;i<re.size();i++){
System.out.println(re.get(i));
}
}
网友评论