LeetCode每日一练【22】
Generate Parentheses
我的代码
介绍
不是我写的, 我可写不出来, 看懂都费劲!
思路
- 递归运算, 内嵌函数
- 创建两个指针: left(左括号数量),right(右括号数量),curr(临时存储的字符串)
- 首先判断 left === n && right === n, 如果都等于的话, 证明结果符合条件, 将curr入组, 返回上一层即可
- 如果不全等于的话, 先判断left < n ?, 因为右括号必定在左括号前面, 如果为true, 继续将(加到curr中, 继续执行下一层递归
- 再判断right < left ?, 因为左括号必定在left之后, 且数量必须小于当前的右括号, 如果为true, 继续将)加到curr中, 继续执行下一层递归.
- 调用内嵌函数: dfs(0, 0, '')
- 返回最终结果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)) // ['()']
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号