I did a question on leetcode, but for the string type, the push_back concatenation character failed the test, but changed to the plus sign to concatenate the character and passed it.
topic link
my two codes:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string part = "";
__generateParenthesis(res, part, n, n);
return res;
}
void __generateParenthesis(vector<string> &res, string part, int left, int right) {
if (left == 0 && right == 0) {
res.push_back(part);
return ;
}
if (left > 0) {
part.push_back("(");
__generateParenthesis(res, part, left - 1, right);
}
if (right > 0 && left < right) {
part.push_back(")");
__generateParenthesis(res, part, left, right - 1);
}
}
};
the above is not passable, but the following is passable:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string part = "";
__generateParenthesis(res, part, n, n);
return res;
}
void __generateParenthesis(vector<string> &res, string part, int left, int right) {
if (left == 0 && right == 0) {
res.push_back(part);
return ;
}
if (left > 0) {
// part.push_back("(");
__generateParenthesis(res, part + "(", left - 1, right);
}
if (right > 0 && left < right) {
// part.push_back(")");
__generateParenthesis(res, part + ")", left, right - 1);
}
}
};
I don"t quite understand. I hope the seniors can give me some guidance.