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&v,vector>&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 > combine(int n, int k) {
        vectorv;
    vector>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;
    }
};


你可能感兴趣的:(2017校招编程题)