Leetcode 22 括号生成

2019-11-01  本文已影响0人  hekirakuno

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

例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

思路:回溯法(参考学长大神的解做的)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<String>();
        if(n<1){
            return ans;
        }
        //初始状态
        //最终结果集,当前串,已有左括号数,右括号数,要求的括号对
        ans = returnSearch(ans,"",0,0, n);
        return ans;
    }
    public List<String> returnSearch(List<String> ans,String temp,int left,int right,int n){
        if(left>n||right>left){
            return ans;
        }
        if(left==right&&left==n){
            ans.add(temp);
        }
        ans = returnSearch(ans,temp + "(",left+1,right,n);
        ans = returnSearch(ans,temp + ")",left,right+1,n);
        return ans;
    }
}
上一篇下一篇

猜你喜欢

热点阅读