Thursday, December 3, 2015

257. Binary Tree Paths (easy)

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

 

Example 1:

Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]

Example 2:

Input: root = [1]
Output: ["1"]

 

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • -100 <= Node.val <= 100
A:  
递归,同时传入路径作为String参数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> V;
helper(root, V, to_string(root->val));
return V;
}

private:
void helper(TreeNode* root, vector<string>& V,
string pre) { // root is not null
if (!root)
return;
if (!root->left && !root->right) {
V.push_back(pre);
}
if (root->left) {
helper(root->left, V, pre + "->" + to_string(root->left->val));
}
if (root->right) {
helper(root->right, V, pre + "->" + to_string(root->right->val));
}
}
};


*************2nd pass**********没有用helper Function*********
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {// root is not NULL
vector<string> V;
if(!root->left && ! root->right){
V.push_back(to_string(root->val));
}
if(root->left){
auto leftRes = binaryTreePaths(root->left);
for(auto s: leftRes){
V.push_back(to_string(root->val) + "->" + s);
}
}
if(root->right){
auto rightRes = binaryTreePaths(root->right);
for(auto s: rightRes){
V.push_back(to_string(root->val) + "->" + s);
}
}
return V;
}
};





********Iteratively,  using a stack ****************
但是这样,需要考虑该节点只有一个child 都情况,因此需要判断其有几个child。





Wednesday, December 2, 2015

Additive Number

Q:
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
For example:
"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.
Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.
Follow up:
How would you handle overflow for very large input integers?
A:

import java.math.BigInteger;

public class Solution {
    public boolean isAdditiveNumber(String num) {
        for(int i =1;i<= num.length()/2;i++){ // i is the end of the index for value a, exclusive
            if(num.charAt(0)=='0' && i != 1)
                break;
            BigInteger a = new BigInteger(num.substring(0,i));
            for(int j = i; j< num.length()-1; j++){ // j is the end of the index for value b, inclusive
                if(num.charAt(i) =='0' && j != i)
                    break;
                BigInteger b = new BigInteger(num.substring(i,j+1));
                if(helper(a, b, num.substring(j+1)))
                    return true;
            }
        }
        return false;
    }
    private boolean helper(BigInteger a,BigInteger b , String str){
        if(str.length()==0)
            return true;
        a = a.add(b);
        String ss = a.toString();
        return str.indexOf(ss)==0 && helper(b,a,str.substring(ss.length()));
    }
}


Mistake:
 第一遍,没有考虑数字溢出的情况。

这里,容易出错的地方,就是i,j的终止条件。

 *********2nd pass************
Using String addition,  instead of using BigInteger

public class Solution {
    public boolean isAdditiveNumber(String num) {
        for(int i =1;i<= num.length() /2;i++){ // for every end i
            for(int j =i+1;j<num.length() ; j++){
                if(isValid(num.substring(0,i),num.substring(i,j),num.substring(j)))
                    return true;
            }
        }
        return false;
    }
    private boolean isValid(String a, String b, String rest){
        if(rest.length() == 0)
            return true;
        if(a.charAt(0)=='0'  && a.length()!=1 )
            return false;
        if(b.charAt(0)=='0'  && b.length()!=1 )
            return false;
        String c = add(a,b, 0);
        return rest.indexOf(c)==0 && isValid(b,c,rest.substring(c.length()));
    }
    
    
    private String add(String a ,String b, int c){
        if(a.length()==0 && b.length()==0)
            return c==0?"":""+c;
        int x = 0, y = 0;
        if( a.length() !=0){
            x = a.charAt(a.length()-1)-'0';
            a = a.substring(0,a.length()-1);
        }
        if( b.length() !=0){
            y = b.charAt(b.length()-1)-'0';
            b = b.substring(0,b.length()-1);
        }        
        int res = (x+y+c)%10;
        c = (x+y+c)/10;
        return add(a, b , c)+res;
    }
}

 the parameter for i, and j both caused error





Tuesday, December 1, 2015

Word Pattern

Q:
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
A:

就是简单的双映射

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        String[] A= str.split("\\s+");
        Map<Character, String> map1 = new HashMap();
        Map<String,Character> map2 = new HashMap();
        if(pattern.length() != A.length)
            return false;
        for(int i =0;i< pattern.length();i++){
            char ch = pattern.charAt(i);
            String ss = A[i];
            if(map1.containsKey(ch) ){
                if(! map1.get(ch).equals(ss))
                    return false;
            }
            map1.put(ch,ss);
            // check reverse
            if(map2.containsKey(ss)){
                if(! map2.get(ss).equals(ch))
                    return false;
            }
            map2.put(ss, ch);
        }
        return true;
    }
}

Errors:
好久没刷题了, check String相等的时候, 直接用了等号

Wednesday, November 11, 2015

308. Range Sum Query 2D - Mutable --------H

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10

Note:

  1. The matrix is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRegion function is distributed evenly.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.
A:

就是建立一个2D数组。保存从原点到该位置的和
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class NumMatrix {
public:
    NumMatrix(vector<vector<int>>& matrix) {
        m = matrix.size();
        if(m==0){
            return;
        }
        n = matrix[0].size();
        M = vector<vector<long>>(m+1,vector<long>(n+1,0));
        for(int i =1;i<=m;i++){
            for(int j = 1; j<=n; j++){
                M[i][j] = matrix[i-1][j-1] + M[i-1][j]+M[i][j-1] - M[i-1][j-1];
            }
        }
    }
    
    void update(int row, int col, int val) {
        long orig = M[row+1][col+1] - M[row][col+1] - M[row+1][col] + M[row][col];
        long diff = val - orig;
        for(int i = row+1; i<=m;i++){
            for(int j = col+1; j<=n; j++){
                M[i][j] += diff;
            }
        }
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        long downRight = M[row2+1][col2+1];
        long topRight = M[row1][col2+1];
        long downLeft = M[row2+1][col1];
        long topLeft = M[row1][col1];
        return int( downRight - topRight - downLeft + topLeft  );
    }
private:
    vector<vector<long>> M;
    int m=0, n = 0;
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * obj->update(row,col,val);
 * int param_2 = obj->sumRegion(row1,col1,row2,col2);
 */

Note:
注意的一点是:求的row1 -1 , col-1的交叉
因为在constructor中没有检测matrix == null,耽误了1个小时,╮(╯▽╰)╭



Bulls and Cows

Q:
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
For example:
Secret number:  "1807"
Friend's guess: "7810"
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return "1A3B".
Please note that both secret number and friend's guess may contain duplicate digits, for example:
Secret number:  "1123"
Friend's guess: "0111"
In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B".
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

A:
 就是简单的对比,数即可(首先数出完全匹配的)再用HashMap,找到所有的secret中出现的 。 再便利guess,确认即可

public class Solution {
    public String getHint(String secret, String guess) {
        int A = 0,AB =0;
        Map<Character,Integer> map = new HashMap();
        for(int i =0;i<secret.length();i++){
            char ch1 = secret.charAt(i);
            if( ch1==guess.charAt(i))
                A++;
            if(map.containsKey(ch1)){
                map.put(ch1,map.get(ch1)+1);
            }else{
                map.put(ch1,1);
            }
        }
        // check guess string for new 
        for(int i =0;i<secret.length();i++){
            char ch = guess.charAt(i);
            if(map.containsKey(ch)){
                AB++;
                map.put(ch,map.get(ch)-1);
                if(map.get(ch)==0)
                    map.remove(ch);
            }
        }
        return ""+A+"A"+(AB-A)+"B";
    }
}



*************************利用0-9这个特性,创建2个数组*****************

public class Solution {
    public String getHint(String secret, String guess) {
        int A = 0, AB=0;
        int C1[] = new int[10];
        int C2[] = new int[10];
        for(int i =0;i<secret.length();i++){
            char ch1 = secret.charAt(i);
            char ch2 = guess.charAt(i);
            if(ch1==ch2)
                A++;
            C1[ch1-'0']++;
            C2[ch2-'0']++;
        }
        for(int i =0;i<10;i++)
            AB+= Math.min(C1[i],C2[i]);
        return ""+A+"A"+(AB-A)+"B";
    }
}












303. Range Sum Query - Immutable -E

Q:
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.
A:

class NumArray {
public:
    NumArray(vector<int>& nums) {
        int sum = 0;
        for(auto v: nums)
        {
            sum += v;
            V.push_back(sum);
        }
    }
    
    int sumRange(int i, int j) {
        int pre = i>0? V[i-1] : 0;
        return V[j] - pre;
    }
private:
    vector<int> V; // assume no overflow on int 
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * int param_1 = obj->sumRange(i,j);
 */

Tuesday, November 10, 2015

Add Digits

Q:
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
             Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?

A:

----------递归+循环
class Solution {
public:
    int addDigits(int num) {
       
        while(num >= 10)
        {
            int res = 0;
            while(num > 0)
            {
                res += num %10;
                num /= 10;
            }
            num = res;
        }
        return num;
    }
};
-----------------每次进位的时候,其实都是在下次的值上增加了1—————————

public class Solution {
    public int addDigits(int num) {
        int s = 0;
        while(num !=0){
            s += num%10;
            if(s>=10)
                s = s%10  +1;
            num /= 10;
        }
        return s;
    }
}

***********************一行代码,的解法 *******************************
class Solution {
public:
    int addDigits(int num) {
       return 1+((num-1)%9);
    }
};
下面这个也是:

public int addDigits(int num) {
    return num == 0 ? 0 : (num % 9 == 0 ? 9 : num % 9);
}