412
法一:
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> result;
for(int i = 1; i <= n; i++)
{
char tmp[10];
if(!(i % 15))
{
result.push_back("FizzBuzz");
}
else
if(!(i%3))
{
result.push_back("Fizz");
}
else
if(!(i%5))
{
result.push_back("Buzz");
}
else
{
sprintf(tmp,"%d",i);
result.push_back(tmp);
}
}
return result;
}
};
法二:
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> ret_vec(n);
for(int i=1; i<=n; ++i)
{
if(i%3 == 0)
{
ret_vec[i-1] += string("Fizz");
}
if(i%5 == 0)
{
ret_vec[i-1] += string("Buzz");
}
if(ret_vec[i-1] == "")
{
ret_vec[i-1] += to_string(i);
}
}
return ret_vec;
}
};
404
法一:这个思路解法还算是清晰,就是把每次计算的值最终累加起来,判断做节点是否是叶子。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
if (root->left && !root->left->left && !root->left->right) return root->left->val + sumOfLeftLeaves(root->right);
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
法二: 这个代码逻辑更简单。但是我发现这里的result得定义成全局变量,但是测试的时候我定义为static是可以的,但是提交却不可以。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int result = 0;
int sumOfLeftLeaves(TreeNode* root) {
TreeNode *left_part = NULL;
TreeNode *right_part = NULL;
if(root != NULL)
{
left_part = root->left;
right_part = root->right;
if(left_part)
{
if(left_part->left == NULL && left_part->right == NULL)
{
result += left_part->val;
}
else
{
result = sumOfLeftLeaves(left_part);
}
}
if(right_part)
if(right_part->left != NULL || right_part->right != NULL)
result = sumOfLeftLeaves(right_part);
}
return result;
}
};