Java DP use % operator to simplify the code


  • 0

    we can combine 3 lines into 2 by using another loop and % operator

    public class Solution {
        public int minCost(int[][] costs) {
            int n = costs.length;
            if (n == 0)
                return 0;
            int[][] min = new int[n][3];
            for (int j = 0; j <= 2; j++)
                min[0][j] = costs[0][j];
            for (int i = 1; i <= n - 1; i++) 
                for (int j = 0; j <= 2; j++) 
                    min[i][j] = costs[i][j] + Math.min(min[i - 1][(j + 1) % 3], min[i - 1][(j + 2) % 3]);
            return Math.min(Math.min(min[n - 1][0], min[n - 1][1]), min[n - 1][2]);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.