
括号是成对出现,首先左括号可以放n个,右括号也可以放n个。如果当前左括号放了3了,右括号放了4个,错了,如果左括号放了5个,右括号放了4个。可以,继续放右括号即可。所以可以设计:
1、当前左括号-右括号>0?大于可以放右括号
2、当前左括号还剩下多少个可以放 >0 可以继续放左括号
代码如下:
- public List<String> generateParenthesis(int n) {
- List<String> ans=new ArrayList<>();
- if (n<1){
- return ans;
- }
- char[] path = new char[n * 2];
- process(0,0, n,path,ans);
- return ans;
- }
-
- /**
- *
- * @param index 下标
- * @param leftNum 左括号-右括号还剩下几个
- * @param leftNumAll 左边一共可以放几个
- * @param path
- * @param ans
- */
- private void process(int index, int leftNum, int leftNumAll, char[] path, List<String> ans) {
- if (index==path.length){
- ans.add(String.valueOf(path));
- }else {
- if (leftNum>0){
- path[index]=')';
- process02(index+1,leftNum-1,leftNumAll,path,ans);
- }
- if (leftNumAll>0){
- path[index]='(';
- process02(index+1,leftNum+1,leftNumAll-1,path,ans);
- }
- }
- }