LeetCode练习中等卷

sum-root-to-leaf-numbers

given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

class Solution {
public:
    int dfs(TreeNode *root,int c)//c是上一步计算的结果
    {
         if(root==NULL)return 0;//空节点,返回0
         int val=10*c+root->val;
         if(!root->left&&!root->right)return val;//叶节点,直接返回
         if(root->left&&!root->right) return dfs(root->left,val);
         if(!root->left&&root->right)   return dfs(root->right,val);
         return dfs(root->left,val)+dfs(root->right,val);
    }
    int sumNumbers(TreeNode *root) {
        return dfs(root,0);
    }
};

combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

class Solution {
public:
    void helper(int cur, int n, int k, vector<int>&v,vector<vector<int>>&rs)
{
    if (k == 0)
    {
        //show(v);
        rs.push_back(v);
    }
    for (int i = cur; i <= n; i++)
    {
        v.push_back(i);
        helper(i + 1, n, k - 1, v, rs);
        v.pop_back();
    }
}
    vector<vector<int> > combine(int n, int k) {
        vector<int>v;
    vector<vector<int>>rs;
    helper(1, n, k, v, rs);
    //show(rs);
    return rs;
    }
};

length-of-last-word

Given a string s consists of upper/lower-case alphabets and empty space characters' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s ="Hello World",
return5.

class Solution {
public:
    bool IsRight(char c)
{
    return (c >= 'a'&&c <= 'z') || (c >= 'A'&&c <= 'Z');
}
    int lengthOfLastWord(const char *s) {
        int i = 0, j = 0;
    int count = 0;
    while (*(s + i) != '\0')
    {
        //找到一个字母
        while (*(s + i) != '\0'&&!IsRight(*(s + i)))i++;//找到了一个字母
        j = i;
        while (*(s + j) != '\0'&&IsRight(*(s + j)))j++;//直到下一个非字母
        //count = count > (j - i) ? count : (j - i);
        //cout << "i=" << i << " j=" << j << endl;
        if (j != i) count = j - i;
        i = j;
    }
    return count;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值