W********e 发帖数: 45 | 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, righ... 阅读全帖 |
|
h****n 发帖数: 1093 | 2 第一题
vector GetNumOfUnival(TreeNode * root)
{
vector res;
helper(root, res);
return res;
}
int helper(TreeNode * root, vector & res)
{
if(root==NULL)
return 0;
int leftNum = helper(root->left);
int rightNUm = helper(root->right);
if(leftNum==-1||rightNum==-1)
return -1;
else if(leftNum!=rightNum)
return -1;
else
{
res.push_back(root);
return leftNum+rightNum+1;
}
}
第二题
... 阅读全帖 |
|
o****d 发帖数: 2835 | 3 他的目的是把sample的最后一个entry去掉
其实他想做的就是 sample.pop_back(),把之前sample.push_back('(')的清掉
(说实话,感觉他这么写有点难看)
另外 如果CombinationPar的第二个参数 不是引用(string& sample)的话
就不用额外做这个处理了
sample.push_back('(');
CombinationPar(result, sample, deep+1, n, leftNum+1, rightNum);
sample.resize(sample.size()-1); |
|
|