LeetCode每日一练【22】

Generate Parentheses

我的代码

介绍

不是我写的, 我可写不出来, 看懂都费劲!

思路

  1. 递归运算, 内嵌函数
  2. 创建两个指针: left(左括号数量), right(右括号数量), curr(临时存储的字符串)
  3. 首先判断 left === n && right === n, 如果都等于的话, 证明结果符合条件, 将curr入组, 返回上一层即可
  4. 如果不全等于的话, 先判断left < n ?, 因为右括号必定在左括号前面, 如果为true, 继续将(加到curr中, 继续执行下一层递归
  5. 再判断right < left ?, 因为左括号必定在left之后, 且数量必须小于当前的右括号, 如果为true, 继续将)加到curr中, 继续执行下一层递归.
  6. 调用内嵌函数: dfs(0, 0, '')
  7. 返回最终结果res

代码

/*
 * @Author: fox
 * @Date: 2022-05-03 14:04:03
 * @LastEditors: fox
 * @LastEditTime: 2022-05-04 15:08:44
 * @Description: https://leetcode.com/problems/generate-parentheses/
 */

/**
 * @description: Runtime: 96.06%  Memory Usage: 90.06%
 * @param {number} n
 * @return {string[]}
 */
const generateParenthesis = (n) => {
    const res = [];
    const dfs = (left, right, curr) => {
        if (left === n && right === n) { // 如果 ( 和 ) 都全部入栈 直接返回结果
            res.push(curr);
            return;
        }

        if (left < n) {
            console.log('left < n: curr: ', `${curr}(`);
            dfs(left + 1, right, `${curr}(`);
        }

        if (right < left) {
            console.log('right < left: curr: ', `${curr})`);
            dfs(left, right + 1, `${curr})`);
        }
    }

    dfs(0, 0, ''); // 执行内嵌函数
    return res;
};

let n = 3;
console.log(generateParenthesis(n)) // ["((()))","(()())","(())()","()(())","()()()"]

n = 1
console.log(generateParenthesis(n)) // ['()']
posted @ 2022-05-04 15:24  白い故雪  阅读(13)  评论(0编辑  收藏  举报