655. 输出二叉树

代码实现(自解)
class Solution {
private:
int getHeight(TreeNode* root) {
if (!root) return 0;
return max(getHeight(root->left), getHeight(root->right)) + 1;
}
public:
vector<vector<string>> printTree(TreeNode* root) {
int m = getHeight(root);
int n = round(pow(2, m)) - 1;
vector<vector<string>> ans(m, vector<string>(n, ""));
map<TreeNode*, int> loc;
loc[root] = (n - 1) / 2;
queue<TreeNode*> qu;
qu.push(root);
int height = 0;
int sz = 0;
TreeNode* tmp;
while (!qu.empty()) {
sz = qu.size();
while (sz--) {
tmp = qu.front();
qu.pop();
ans[height][loc[tmp]] = to_string(tmp->val);
if (tmp->left) {
qu.push(tmp->left);
loc[tmp->left] = loc[tmp] -
round(pow(2, m - 2 - height));
}
if (tmp->right) {
qu.push(tmp->right);
loc[tmp->right] = loc[tmp] +
round(pow(2, m - 2 - height));
}
}
height++;
}
return ans;
}
};
49. 字母异位词分组

代码实现(自解)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
int n = strs.size();
vector<string> v1 = strs, v2;
for (string& str : v1) {
sort(str.begin(), str.end());
}
vector<bool> used(n, false);
for (int i = 0; i < n; i++) {
if (used[i]) continue;
v2.clear();
v2.push_back(strs[i]);
for (int j = i + 1; j < n; j++) {
if (used[j]) continue;
if (v1[j] == v1[i]) {
v2.push_back(strs[j]);
used[j] = true;
}
}
ans.push_back(v2);
}
return ans;
}
};
43. 字符串相乘

代码实现(部分看题解)
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") return "0";
int m = num1.size();
int n = num2.size();
vector<int> arr(m + n);
int n1, n2;
for (int i = m - 1; i >= 0; i--) {
n1 = num1[i] - '0';
for (int j = n - 1; j >= 0; j--) {
n2 = num2[j] - '0';
arr[i + j + 1] += n1 * n2;
}
}
for (int i = m + n - 1; i > 0; i--) {
arr[i - 1] += arr[i] / 10;
arr[i] = arr[i] % 10;
}
int index = arr[0] ? 0 : 1;
string ans = "";
while (index < m + n) {
ans.push_back(arr[index] + '0');
index++;
}
return ans;
}
};