一. 题目
描述
给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
“((()))”, “(()())”, “(())()”, “()()()”, “()(())”,
示例1
输入:
1
返回值:
["()"]
示例2
输入:
2
复制
返回值:
["(())","()()"]
二. 思路
模拟加入左括号,右括号可以生成合法括号组合的过程直至所有左右括号都加入生成一个括号组合然后记录返回.
- 生成完整括号组合标志为加入的右括号个数r=n个括号数
- 可以合法加入左括号的条件为,左括号个数l < n个括号数
- 可以合法加入右括号的条件为, 左括号个数l> r右括号个数
三. 代码
import java.util.*;
public class Solution {
/**
*
* @param n int整型
* @return string字符串ArrayList
*/
public ArrayList<String> generateParenthesis (int n) {
// write code here
ArrayList<Character> stack = new ArrayList();
ArrayList<String> result = new ArrayList<>();
int[] count = new int[1];
fun(n, 0, 0, stack, result, count);
return result;
}
public void fun (int n, int l, int r, ArrayList<Character> stack, ArrayList<String> result, int[] count) {
if (stack.size() == 2 * n) {
String temp = "";
for (int i = 0; i < stack.size(); i++) {
temp = temp + stack.get(i);
}
result.add(new String(temp));
count[0] ++;
return;
}
if (l < n ) {
int size = stack.size();
stack.add('(');
l++;
fun(n, l, r, stack, result, count);
stack.remove(size);
l--;
}
if (l > r) {
int size = stack.size();
stack.add( ')');
r++;
fun(n, l, r, stack, result, count);
stack.remove(size);
r--;
}
}
}
四. 回溯法归纳总结(TODO)
- 回溯法
https://baike.baidu.com/item/%E5%9B%9E%E6%BA%AF%E6%B3%95/86074
五. 参考资料
-
n对括号的排列组合
https://blog.csdn.net/dengyingjie123/article/details/83039580 -
(递归)四对括号有多少种合法组合
https://blog.csdn.net/qq_42396168/article/details/105844168 -
回溯算法最佳实践:括号生成
https://labuladong.gitbook.io/algo/mu-lu-ye-3/mu-lu-ye/he-fa-kuo-hao-sheng-cheng