Monday, September 9, 2013

Triangle@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
» Solve this problem

It cost some of my time to think about it. After search it online, I got the key point is DP and we can replace the value in triangle, so that we can do it in place.

The algorithm is easy.
Do it bottom up, sum up the smaller elements that the current one can reach in next level. Return the first node in first level in the end.


2 comments:

  1. I think the variable "col" should be named "row" to be more understandable.

    ReplyDelete
  2. I wrote in a recursive way, but is says that I exceed time limit, do you know why?
    int minimumTotal(vector > &triangle) {
    return minimumTotalDFS(triangle, 0, 0);
    }

    int minimumTotalDFS(vector > &triangle, int lvl, int idx){
    if(lvl >= triangle.size() - 1)
    return triangle[lvl][idx];

    int leftMin = minimumTotalDFS(triangle, lvl + 1, idx);
    int rightMin = minimumTotalDFS(triangle, lvl + 1, idx + 1);

    return triangle[lvl][idx] + min(leftMin, rightMin);
    }

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...