美文网首页
[LeetCode] 22. Generate Parenthe

[LeetCode] 22. Generate Parenthe

作者: 弱花 | 来源:发表于2018-11-02 11:39 被阅读0次

原题


思路:
利用DFS,搜索每一种情况,同时先加“(”后加")",保证()匹配正确。

最近开始学习前端,尝试用js来写。

const generate = function (res,content, left, right) {
    if (left === 0) {
        res.push(content + ')'.repeat(right));
        return;
    }
    if (left <= right && left > 0) {
        generate(res,content + '(', left - 1, right);
    }
    if (right > 0) {
        generate(res,content + ')', left, right - 1);
    }
}

var generateParenthesis = function(n) {
    const res = [];
    generate(res,'', n, n);
    return res;
};

相关文章

网友评论

      本文标题:[LeetCode] 22. Generate Parenthe

      本文链接:https://www.haomeiwen.com/subject/ppiqxqtx.html