LeetCode问题#22如何调试递归问题?

时间:2020-05-30 03:43:02

标签: c++ recursion depth-first-search parentheses

LeetCode 22. Generate Parentheses

给出n对括号,编写一个函数以生成格式正确的括号的所有组合。

例如,假设n = 3,则解决方案集为:

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

我不太确定下面的代码出了什么问题。我正在使用dfs生成格式正确的括号的所有组合,并且通过跟踪剩余的左方括号数和剩余的右方括号数来做到这一点。但是,在我从递归调用返回后,剩余的括号数量有所不同,这导致会有更多的括号。

vector<string> generateParentheses(int n) {
    vector<string> result;
    dfs(result, "", n, n);
    return result;
}

void dfs(vector<string> &result, string s, int num_left, int num_right){
    if(num_left == 0 && num_right == 0){
        result.push_back(s);
    }
    if(num_left > 0){
        dfs(result, s += "(", num_left - 1, num_right);
    }
    if(num_right > 0 && num_right > num_left){
        dfs(result, s += ")", num_left, num_right - 1);
    }
}

0 个答案:

没有答案