leetcode 22题

Posted by franki on June 4, 2021

leetcode 22题 括号生成

示例1

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例2

输入:n = 1
输出:["()"]

思路

全排列型问题,可以通过回溯法解答

代码

/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function(n) {
    if (n === 0) {
        return [];
    }
    const res = [];
    findGrenerateParentthesis(n, n, "", res);
    return res;
};

function findGrenerateParentthesis(lindex, rindex, str, res) {
    if (lindex === 0 && rindex === 0) {
        res.push(str);
        return;
    }
    if (lindex > 0) {
        findGrenerateParentthesis(lindex-1, rindex, str + "(", res);
    }
    if (rindex > 0 && lindex < rindex) {
        findGrenerateParentthesis(lindex, rindex-1, str + ")", res);
    }
}

复杂度分析:

  • 时间复杂度: O(N)
  • 空间复杂度:O(N^2)