This is from leetcode: http://www.programcreek.com/2013/01/leetcode-triangle-java/
[ [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).
The key observation here is that viewing this triangle as a tree, for any given subtree, the minimum path sum is the minimum of all of its subtrees plus the number at the root. At the leaf level, the minimum path sum is the value at the leaves.
If we use dynamic programming, keep track of the minimum path sum at lower level, and then going up to calculate the min path sum at higher level.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int minPath(List<int[]> input){ | |
int levels = input.size(); | |
int[][] dp = new int[levels][levels]; | |
//we start at the bottom | |
//here the min path sum is the numbers at the bottom | |
dp[levels-1] = input.get(levels-1); | |
//now we go up | |
for(int l=levels-2; l>=0; l--){ | |
for(int pos = 0; pos<=l; pos++){ | |
dp[l][pos] = Math.min(dp[l+1][pos], dp[l+1][pos+1]) + input.get(l)[pos]; | |
} | |
} | |
return dp[0][0]; | |
} | |
Further observation of the dynamic programming solution is that we don't need a 2D table, in stead we can use an array and keep on updating it when going up.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int minPathBetter(List<int[]> input){ | |
int levels = input.size(); | |
int[] dp = new int[levels]; | |
//we start at the bottom | |
//here the min path sum is the numbers at the bottom | |
dp = input.get(levels-1); | |
//now we go up | |
for(int l=levels-2; l>=0; l--){ | |
for(int pos = 0; pos<=l; pos++){ | |
dp[pos] = Math.min(dp[pos], dp[pos+1]) + input.get(l)[pos]; | |
} | |
} | |
return dp[0]; | |
} |
This is actually a variation of Dijkstra.
ReplyDeleteGood observation. Dijkstra is top to bottom, bfs with a queue. This is bottom to top using post-order search.
ReplyDelete