[LeetCode]Paint House II

public class Solution {
    public int minCostII(int[][] costs) {
        int n = costs.length;
        if (n == 0) {
            return 0;
        }
        int k = costs[0].length;
        if (k == 0) {
            return 0;
        }
        if (k == 1) {
            return costs[0][0];
        }
        int[] record = new int[k];
        for (int i = 0; i < n; i++) {
            int index = record[0] < record[1] ? 0 : 1;
            int min = Math.min(record[0], record[1]);
            int sec_min = Math.max(record[0], record[1]);
            for (int j = 2; j < k; j++) {
                if (record[j] < min) {
                    index = j;
                    sec_min = min;
                    min = record[j];
                } else if (record[j] < sec_min) {
                    sec_min = record[j];
                }
            }
            for (int j = 0; j < k; j++) {
                if (j == index) {
                    record[j] = sec_min + costs[i][j];
                } else {
                    record[j] = min + costs[i][j];
                }
            }
        }
        int result = Integer.MAX_VALUE;
        for (int num : record) {
            result = Math.min(result, num);
        }
        return result;
    }
}

 

posted @ 2015-12-01 07:04  Weizheng_Love_Coding  阅读(140)  评论(0编辑  收藏  举报