教育改变生活

标题: LeetCode真题-生成括号 [打印本页]

作者: 一秉    时间: 2020-8-11 16:32
标题: LeetCode真题-生成括号
题目描述
给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()(())", "()()()"
输入:1
输出:["()"]
示例2
输入:2
输出:["(())","()()"]
代码实现:
import java.util.*;


public class Solution {
    /**
     *
     * @param n int整型
     * @return string字符串ArrayList
     */
    public ArrayList<String> generateParenthesis (int n) {
        // write code here
        ArrayList<String> result = new ArrayList<String>();
        generateCycle(n, 0, 0, "", result);
        return result;
    }
     
    public void generateCycle(int n, int left, int right, String s, ArrayList<String> res){
        if (right == n){
            res.add(s);
            return ;
        }
         
        if (left < n){
            generateCycle(n, left+1, right, s+'(', res);
        }
         
        if (left > right){
            generateCycle(n, left, right+1, s+')', res);
        }
    }
}





欢迎光临 教育改变生活 (http://bbs.goldoar.com/) Powered by Discuz! X3.2