I have a question about C++ string storing. Wish to know why I got different answers between these two ways.
This is a Leetcode problem #22 Generate Parentheses:
The first one is my final modified answer and finally got the correct answer which accepted on leetcode compiler.
Two ways inputs are same as "2" And answer might be ["(())","()()"]
1. Correct
class Solution {
public:
void matchParenthesis(vector<string> &result,string thisResult,int n ,int left , int right){
//left= 已使用“(”個數
if(left==n && right==n){
result.push_back(thisResult);
thisResult="";
}else{
if(left<n && left>=0){
matchParenthesis(result,thisResult+"(",n,left+1,right);
}
if(right<left && right<n){
matchParenthesis(result,thisResult+")",n,left,right+1);
}
//cout<<thisResult<<"\n";
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
string thisResult;
matchParenthesis(result,thisResult,n,0,0);
return result;
}
};
2. This was my wrong code before accepting.
class Solution {
public:
void matchParenthesis(vector<string> &result,string thisResult,int n ,int left , int right){
//left= 已使用“(”個數
if(left==n && right==n){
result.push_back(thisResult);
thisResult="";
}else{
if(left<n && left>=0){
thisResult+="(";
matchParenthesis(result,thisResult,n,left+1,right);
}
if(right<left && right<n){
thisResult+=")";
matchParenthesis(result,thisResult,n,left,right+1);
}
//cout<<thisResult<<"\n";
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
string thisResult;
matchParenthesis(result,thisResult,n,0,0);
return result;
}
};
input:2 and output: ["(())","(()()"]
The different code as below in the "else" section: 1.
if(left<n && left>=0){
matchParenthesis(result,thisResult+"(",n,left+1,right);
}
if(right<left && right<n){
matchParenthesis(result,thisResult+")",n,left,right+1);
}
if(left<n && left>=0){
thisResult+="(";
matchParenthesis(result,thisResult,n,left+1,right);
}
if(right<left && right<n){
thisResult+=")";
matchParenthesis(result,thisResult,n,left,right+1);
}
I desire to know why the first solution parameter in recursion
matchParenthesis(result,thisResult+"(",n,left+1,right);
parameter thisReuslt+"("
is different from Solution 2, which stores "(" into thisResult
like thisResult+="(";
and then set the second parameter like matchParenthesis(result,thisResult,n,left+1,right);
In my recognition, they are the same between " first insert "(" into the original parameter thisResult " and direct set the parameter "thisResult" +"(". But it seems not the same, I want to know what is different.
Thank you stackoverflow, thank you everyone. Sorry for that poor English.