2014年5月8日星期四

Recursive Solution - Triangle

The idea is to recursive calling the function with depth and pos…

Dynamic programing and recursive are two special technologies, which should always  be in mind if not sure what to do!!!

public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        if(triangle == null || triangle.size() == 0){
            return 0;
        }
        return minTotalOps(triangle, 0, 0);
    }
   
    private int minTotalOps(ArrayList<ArrayList<Integer>> triangle, int depth, int pos){
        if(depth + 1 == triangle.size()){
            if(pos + 1 < triangle.get(depth).size()){
                return Math.min(triangle.get(depth).get(pos), triangle.get(depth).get(pos + 1));
            }else{
                return triangle.get(depth).get(pos);
            }
        }
       
        return triangle.get(depth).get(pos) + Math.min(minTotalOps(triangle, depth + 1, pos), minTotalOps(triangle, depth + 1, pos + 1));
    }
}

没有评论: