f*a
1 楼
Unique Binary Search Trees II
class Solution {
public:
// return all combinations of trees with given start/end;
// if start>end return single item NULL in vector.
vector Helper(vector array, int s, int e) {
if (s>e) return vector(1, NULL);
// each item in the array range can be root.
vector combo;
for (int i=s; i<=e; ++i) {
vector left = Helper(array, s, i-1);
vector right = Helper(array, i+1, e);
// compose combo with combinations of all left/right
for (int j=0; i for (int k=0; k TreeNode* root = new TreeNode(array[i]);
root->left = left[j];
root->right = left[k];
combo.push_back(root);
}
}
}
return combo;
}
vector generateTrees(int n) {
// prepare an array
vector array;
for (int i=1; i<=n; ++i) {
array.push_back(i);
}
return Helper(array, 0, n-1);
}
};
[发表自未名空间手机版 - m.mitbbs.com]
class Solution {
public:
// return all combinations of trees with given start/end;
// if start>end return single item NULL in vector.
vector
if (s>e) return vector
// each item in the array range can be root.
vector
for (int i=s; i<=e; ++i) {
vector
vector
// compose combo with combinations of all left/right
for (int j=0; i
root->left = left[j];
root->right = left[k];
combo.push_back(root);
}
}
}
return combo;
}
vector
// prepare an array
vector
for (int i=1; i<=n; ++i) {
array.push_back(i);
}
return Helper(array, 0, n-1);
}
};
[发表自未名空间手机版 - m.mitbbs.com]