Thursday, February 5, 2015

Leetcode--Dungeon Game

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2 (K)   -3         3
-5         -10       1
10        30        -5 (P)
Notes:
The knight's health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
Solution:
This problem can be solved through a table-filling Dynamic Programming technique, similar to other "grid walking" problems:
To begin with, we should maintain a 2D array D of the same size as the dungeon, where D[i][j] represents the minimum health that guarantees the survival of the knight for the rest of his quest BEFORE entering room(i, j). Obviously D[0][0] is the final answer we are after. Hence, for this problem, we need to fill the table from the bottom right corner to left top.
Then, let us decide what the health should be at least when leaving room (i, j). There are only two paths to choose from at this point: (i+1, j) and (i, j+1). Of course we will choose the room that has the smaller D value, or in other words, the knight can finish the rest of his journey with a smaller initial health. Therefore we have:
           
min_HP_on_exit = min(D[i+1][j], D[i][j+1])
Now D[i][j] can be computed from dungeon[i][j] and min_HP_on_exit based on one of the following situations:
If dungeon[i][j] == 0, then nothing happens in this room; the knight can leave the room with the same health he enters the room with, i.e. D[i][j] = min_HP_on_exit.
If dungeon[i][j] < 0, then the knight must have a health greater than min_HP_on_exit before entering (i, j) in order to compensate for the health lost in this room. The minimum amount of compensation is "-dungeon[i][j]", so we have D[i][j] = min_HP_on_exit - dungeon[i][j].
If dungeon[i][j] > 0, then the knight could enter (i, j) with a health as little as min_HP_on_exit - dungeon[i][j], since he could gain "dungeon[i][j]" health in this room. However, the value of min_HP_on_exit - dungeon[i][j] might drop to 0 or below in this situation. When this happens, we must clip the value to 1 in order to make sure D[i][j] stays positive: D[i][j] = max(min_HP_on_exit - dungeon[i][j], 1).
Notice that the equation for dungeon[i][j] > 0 actually covers the other two situations. We can thus describe all three situations with one common equation, i.e.:
D[i][j] = max(min_HP_on_exit - dungeon[i][j], 1) , for any value of dungeon[i][j].
Take D[0][0] and we are good to go. Also, like many other "table-filling" problems, the 2D array D can be replaced with a 1D "rolling" array here.
 */
Java code:
public class Solution { 
    public int calculateMinimumHP(int[][] dungeon) { 
        if(dungeon.length == 0) 
            return 0; 
        int m = dungeon.length, n = dungeon[0].length; 
        int[][] dp = new int[m][n]; 
        dp[m - 1][n - 1] = dungeon[m - 1][n - 1] >= 0 ? 1 : -dungeon[m - 1][n - 1] + 1; 
        for(int i = m - 2; i >= 0; i--){ 
            dp[i][n - 1] = Math.max(dp[i + 1][n - 1] - dungeon[i][n - 1], 1); 
        } 
        for(int j = n - 2; j >= 0; j--){ 
            dp[m - 1][j] = Math.max(dp[m - 1][j + 1] - dungeon[m - 1][j], 1); 
        } 
     
        for(int i = m - 2; i >= 0; i--){ 
            for(int j = n - 2; j >= 0; j--){ 
                dp[i][j] = Math.max(1, Math.min(dp[i + 1][j], dp[i]         [j + 1]) - dungeon[i][j]); 
            } 
        } 
        return dp[0][0]; 
    } 
}

Monday, February 2, 2015

Leetcode: Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.

解题思路:作者是 

排序(Sort)
排序思路:对于两个备选数字a和b,如果str(a) + str(b) > str(b) + str(a),则a在b之前,否则b在a之前
按照此原则对原数组从大到小排序即可
时间复杂度O(nlogn)
Python code: 
class MyClass(object):
    # @param num, a list of integers
    # @return a string
    def largestNumber(self, num):
        num = sorted([str(x) for x in num], cmp = self.compare)
        ans = ''.join(num).lstrip('0')
        return ans or '0'

    def compare(self, a, b):
        return [1, -1][a + b > b + a]

Tuesday, January 13, 2015

水中的鱼: [LeetCode] Largest Rectangle in Histogram 解题报告

水中的鱼: [LeetCode] Largest Rectangle in Histogram 解题报告: Given  n  non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rec...

Wednesday, January 7, 2015

Leetcode – Same Tree



Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

Solution 1: from  
 
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null){
            return true;
        }else if(p != null && q != null){
            if(p.val == q.val){
                return isSameTree(p.left, q.left) && isSameTree(q.right, p.right);
            }
        }
 
        return false;
    }
}


Solution 2 from zhang lei

1:    bool isSameTree(TreeNode *p, TreeNode *q) {  
2:      if(!p && !q) return true; 
3:      if(!p || !q) return false;
4:      return (p->val == q->val) &&  
5:           isSameTree(p->left, q->left) &&   
6:           isSameTree(p->right, q->right);      
7:    }

Solution 3 from http://blog.csdn.net/xudli/article/details/8557010  (better one)

public boolean isSameTree(TreeNode p, TreeNode q){
  
  LinkedList Tp = new LinkedList<TreeNode>();
  LinkedList Tq = new LinkedList<TreeNode>();
  
  Tp.offer(p);
  Tq.offer(q);
  
  while(!Tp.isEmpty() && !Tq.isEmpty())
  {
   TreeNode x = (TreeNode) Tp.poll();
   TreeNode y = (TreeNode) Tq.poll();
   
   if (x == null){
    if (y != null) return false;
    else continue;
   }
   else{
    if (y == null || x.val != y.val){
     return false;
    }
   }
   Tp.offer(x.left);
   Tp.offer(x.right);
   Tq.offer(y.left);
   Tq.offer(y.right);
  }
  return true;
 }