LeetCode 22. 括号生成:DFS递归代码调试求助
Hey there! Let's dig into why your DFS approach is generating invalid parentheses combinations. The core issue is how you're modifying the string s during recursive calls.
The Problem: Accidental String Mutation
In your code, when you call dfs(result, s += "(", num_left - 1, num_right);, the s += "(" doesn't just create a new string for the recursive call—it modifies the s variable in the current function's scope.
Here's what goes wrong step by step:
- Start with
s = "",num_left = n,num_right = n. - Enter the
num_left > 0branch, runs += "(", sosbecomes"("in this function. - After the recursive call returns, move to the
num_rightbranch—but nowsis already"(", not the original empty string. When you runs += ")", you're appending to the modifieds, leading to unexpected combinations and extra parentheses.
This mutation of the current function's s causes cross-contamination between your left and right bracket branches.
The Fix: Pass New Strings Instead of Modifying
Instead of changing the existing s, create a new string for each recursive call using s + "(" and s + ")". This way, the original s in the current function stays intact, and each recursive branch gets a fresh copy of the string with the new bracket added.
Here's the corrected code:
#include <vector> #include <string> using namespace std; vector<string> generateParenthesis(int n) { vector<string> result; dfs(result, "", n, n); return result; } void dfs(vector<string> &result, string s, int num_left, int num_right){ // Base case: no brackets left to add if(num_left == 0 && num_right == 0){ result.push_back(s); return; // Exit early to skip unnecessary checks } // Add left bracket if we have remaining ones if(num_left > 0){ dfs(result, s + "(", num_left - 1, num_right); } // Add right bracket only if we have more right brackets left than left if(num_right > num_left){ dfs(result, s + ")", num_left, num_right - 1); } }
Extra Improvements:
- Added a
returnafter pushing the valid string to the result—this avoids running subsequentifchecks when we're done with this branch, making the code a bit more efficient. - Removed the redundant
num_right > 0check in the secondif—sincenum_right > num_leftalready impliesnum_rightis positive (becausenum_leftcan't be negative).
This should generate all valid parentheses combinations correctly now! For n=3, you'll get the exact output you're expecting: ["((()))", "(()())", "(())()", "()(())", "()()()"].
内容的提问来源于stack exchange,提问作者chibiw3n

