LeetCode 22 (Java解法)

使用了遞歸回溯:

public static List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        helper(res,"",0,0,n);
        return res;
    }
    public static void helper(List<String> res,String out,int open,int close,int n) {
        if(out.length() == 2*n) {
            res.add(out);
            return;
        }
        if(open < n) {
            helper(res,out+"(",open+1,close,n);
        }
        if(close < open) {
            helper(res,out+")",open,close+1,n);
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章