letcode括号生成

递归大法,空间换时间

    就是记录左右括号数,一旦右括号数大于左括号数,退出。
    当左右括号数相等,且等于n则为合法解。

  • 使用char数组取代StringBuilder可以减少内存使用,这样每次进行回溯时不需要再去删除末尾一位。
class Solution {
    /**
     * 括号生成
     * */
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        char[] temp = new char[n * 2];
        /**
         * L-左括号数
         * R-右括号数
         * L + R = temp 下标
         * */
        temp[0] = '(';
        deepParenthesis(result, temp, n, 1, 0);
        return result;
    }

    private void deepParenthesis(List<String> result, char[] temp, int n, int L, int R){
        if (L==R && L ==n){
            /** 左右括号数相等,且等于给定括号数 */
            result.add(String.valueOf(temp));
            return;
        }
        /** 左括号数小等于n,且不小于右括号数 */
        if (L <= n && L >= R){
            /** 下一步左括号 */
            temp[L + R] = '(';
            deepParenthesis(result, temp,n, L + 1, R);
            /** 下一步右括号 */
            temp[L + R] = ')';
            deepParenthesis(result, temp,n, L, R + 1);
        }
    }
}
原文地址:https://www.cnblogs.com/bokers/p/15575200.html