leetcode 22 Generate Parentheses

題目

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.spa

For example, given n = 3, a solution set is:code

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]orm

解釋

圖片描述
這是n = 2的狀況.就是從 ( 開始遍歷,假如 ( 的數目大於 ) 的數目 那就返回,這樣是不符合條件的,(ps:這裏的數目是指剩餘的數目,若是左括號剩餘的多,那說明已經匹配好的字符串中多了右括號,這種狀況沒法經過繼續添加括號來知足條件,因此要返回,就像圖中最右邊那個節點同樣)而後其餘的就是照常遍歷就ok.知足left == 0 && right == 0 push到res裏面.blog

代碼

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

var helper = (res, s, left, right) => {
    if (left > right) {
        return;
    }
    
    if (left == 0 && right == 0) {
        res.push(s);
        return;
    }
    if (left > 0) {
        helper(res, s+"(", left-1, right);
    }
    if (right > 0) {
        helper(res, s+")", left, right-1);
    }
};
相關文章
相關標籤/搜索