Leetcode __22. 括号生成

问题描述

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

解题思路

  • 左括号不为0,消耗左括号
  • 右括号不为0,且大于左括号,则消耗右括号
  • 都为0,则出栈,存到list中,直到最后出栈结束。

递归

public class GenerateParenthesis {
    private void method(){
        if(回归条件){
            回归操作;
        }
        if(满足条件1){
            选择条件1的递归;
        }
        if(满足条件2){
            选择条件2的递归;
        }
        if(满足条件n){
            选择条件n的递归;
        }
    }
}

实现

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        work(list,n,n,"");
        return list;
        
    }
    private void work(List<String> list, int right,int left, String path){
        if(right==0&&left==0){
            list.add(path);
       
        }
        if(left!=0){
            work(list,right,left-1,path+"(");
        }
        if(right!=0&&right>left){
            work(list,right-1,left,path+")");
        }
        
    }
}

猜你喜欢

转载自blog.csdn.net/Growing_way/article/details/83588080