问一leetcode题,为什么要resize。题目Generate Parentheses。# JobHunting - 待字闺中
W*e
1 楼
题目是leetcode上的Generate Parentheses。
不理解为什么有时候用DFS需要resize,有时候不需要。下面这第一种是resize了,
resize的意义是什么?:
void CombinationPar(vector& result, string& sample, int deep,
2: int n, int leftNum, int rightNum)
3: {
4: if(deep == 2*n)
5: {
6: result.push_back(sample);
7: return;
8: }
9: if(leftNum 10: {
11: sample.push_back('(');
12: CombinationPar(result, sample, deep+1, n, leftNum+1, rightNum
);
13: sample.resize(sample.size()-1); //?????????????
?
14: }
15: if(rightNum 16: {
17: sample.push_back(')');
18: CombinationPar(result, sample, deep+1, n, leftNum, rightNum+1
);
19: sample.resize(sample.size()-1); //?????????????
?
20: }
但是看另一个人的code,没有这个动作:
class Solution {
public:
void printPar(int l, int r, vector& result, char* str, int idx)
{
if (l < 0 || r < l) return;
if (l == 0 && r == 0)
{
str[idx] = '\0';
result.push_back(string(str));
}
else
{
if (l > 0)
{
str[idx] = '(';
printPar(l-1, r, result, str, idx+1);
//不需要做什么pop或者resize的动作??????????????
??
}
if (r > l)
{
str[idx] = ')';
printPar(l, r-1, result, str, idx+1);
//不需要做什么pop或者resize的动作??????????????
??
}
}
}
vector generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector result;
char* str = new char[2*n+1];
printPar(n, n, result, str, 0);
delete []str;
return result;
}
};
一是不太理解为什么这么样叫做DFS,二是不理解为什么resize,刚入门,请各位指教
!!
不理解为什么有时候用DFS需要resize,有时候不需要。下面这第一种是resize了,
resize的意义是什么?:
void CombinationPar(vector
2: int n, int leftNum, int rightNum)
3: {
4: if(deep == 2*n)
5: {
6: result.push_back(sample);
7: return;
8: }
9: if(leftNum
11: sample.push_back('(');
12: CombinationPar(result, sample, deep+1, n, leftNum+1, rightNum
);
13: sample.resize(sample.size()-1); //?????????????
?
14: }
15: if(rightNum
17: sample.push_back(')');
18: CombinationPar(result, sample, deep+1, n, leftNum, rightNum+1
);
19: sample.resize(sample.size()-1); //?????????????
?
20: }
但是看另一个人的code,没有这个动作:
class Solution {
public:
void printPar(int l, int r, vector
{
if (l < 0 || r < l) return;
if (l == 0 && r == 0)
{
str[idx] = '\0';
result.push_back(string(str));
}
else
{
if (l > 0)
{
str[idx] = '(';
printPar(l-1, r, result, str, idx+1);
//不需要做什么pop或者resize的动作??????????????
??
}
if (r > l)
{
str[idx] = ')';
printPar(l, r-1, result, str, idx+1);
//不需要做什么pop或者resize的动作??????????????
??
}
}
}
vector
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector
char* str = new char[2*n+1];
printPar(n, n, result, str, 0);
delete []str;
return result;
}
};
一是不太理解为什么这么样叫做DFS,二是不理解为什么resize,刚入门,请各位指教
!!