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.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
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
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;
}
};