96. Unique Binary Search Trees && 95. Unique Binary Search Trees II && 241. Different Ways to Add Parentheses && 282. Expression Add Operators

96. Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
 
public class Solution {
    public int numTrees(int n) {
        //numTrees(n) = Sum(numTrees(n-1-i) * numTrees(n-1-i)), where i is [0,n-1]
        if(n==0)
            return 1;
        int[] nums = new int[n+1];
        nums[0] = 1; nums[1] = 1;
        
        for(int i = 2; i<n+1; ++i)
        {
            int totalChildren = i - 1;
            for(int left = 0; left<=totalChildren;++left)
            {
                nums[i]+=nums[left]*nums[totalChildren-left];
            }
        }
        return nums[n];
        
         /*
        public int numTrees(int n) {
            if(n==0)
                return 1;
            if(n <= 2)
                return n;
            
            int total = 0;
            for(int i = 1; i<=n;++i)
            {
                int left = numTrees(i-1);
                int right = numTrees(n-i);
                total += left * right;
            }
            return total;
        }
        */
    }
}

 

95. Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.

Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<TreeNode> generateTrees(int n) {
        return generateTrees(1,n);   
    }
    
    private List<TreeNode> generateTrees(int from, int to) {
        List<TreeNode> results = new ArrayList<TreeNode>();
        if(from > to)
            return results;
        if(from == to){
            results.add(new TreeNode(from));
            return results;
        }
        
        for(int i = from; i<=to; ++i){
            List<TreeNode> left = generateTrees(from, i-1);
            List<TreeNode> right = generateTrees(i+1, to);
            if(left.size() == 0) {
                for(TreeNode r:right){
                    TreeNode root = new TreeNode(i);
                    root.right = r;
                    results.add(root);
                }
            }
            else if(right.size() == 0) {
                for(TreeNode l:left){
                    TreeNode root = new TreeNode(i);
                    root.left = l;
                    results.add(root);
                }
            }
            else{
                for(TreeNode l:left){
                    for(TreeNode r:right){
                        TreeNode root = new TreeNode(i);
                        root.left = l;
                        root.right = r;
                        results.add(root);
                    }
                }
            }
        }
        return results;
    }
}

 

241. Different Ways to Add Parentheses

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.

Example 1

Input: "2-1-1".

((2-1)-1) = 0
(2-(1-1)) = 2

Output: [0, 2]

Example 2

Input: "2*3-4*5"

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10

Output: [-34, -14, -10, -10, 10]

class Solution {
  public List<Integer> diffWaysToCompute(String input) {
    List<Integer> ret = new LinkedList<>();
    for (int i = 0; i < input.length(); ++i) {
      char c = input.charAt(i);
      if (c == '-' || c == '*' || c == '+') {
        for (int left : diffWaysToCompute(input.substring(0, i))) {
          for (int right : diffWaysToCompute(input.substring(i + 1))) {
            if (c == '+')
              ret.add(left + right);
            else if (c == '-')
              ret.add(left - right);
            else if (c == '*')
              ret.add(left * right);
          }
        }
      }
    }
    if (ret.size() == 0)
      ret.add(Integer.valueOf(input));
    return ret;
  }
}

 

282. Expression Add Operators

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or * between the digits so they evaluate to the target value.

Examples: 

"123", 6 -> ["1+2+3", "1*2*3"] 
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
 
public class Solution {
  public List<String> addOperators(String num, int target) {
    List<String> ret = new ArrayList<>();
    if (num == null || num.length() == 0)
      return ret;
    helper(ret, "", 0, num, target, 0, 0);
    return ret;
  }

  /**
   * Iterate through all possibilities to add operators to str,
   * and add to results if target is achieved.
   */
  private void helper(List<String> ret, String currentString, long currentResult, String str, int target, int startInd, long previousNum) {
    if (startInd == str.length()) {
      if (target == currentResult)
        ret.add(currentString);
      return;
    }
    for (int endInd = startInd; endInd < str.length(); ++endInd) {
      //0 cannot be a starting number, unless it is 0 by itself
      if (str.charAt(startInd) == '0' && endInd > startInd)
        //e.g. "105", "05" might be treated as 5
        //so it will errorly return ["1*0+5","1*5","10-5"]
        break;
      Long num = Long.parseLong(str.substring(startInd, endInd + 1));
      if (startInd == 0)
        helper(ret, num.toString(), num, str, target, endInd + 1, num);
      else {
        helper(ret, currentString + "+" + num, currentResult + num, str, target, endInd + 1, num);
        helper(ret, currentString + "-" + num, currentResult - num, str, target, endInd + 1, -num);
        //if previous number is used as a multiplier, we need to remove it from earlier sum
        long product = previousNum * num;
        helper(ret, currentString + "*" + num, currentResult - previousNum + product, str, target, endInd + 1, product);
      }
    }
  }
}

 

 

 
 
posted @ 2016-07-31 08:24  新一代的天皇巨星  阅读(239)  评论(0)    收藏  举报