2 way dp java code
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class Solution {
    public long minCost(int n, int[][] cost) {
        long[][][] dp = new long[n+1][4][4];
        for(int i=0;i<dp.length;i++){
            for(int j=0;j<dp[i].length;j++){
                for(int k=0;k<dp[i][j].length;k++){
                    dp[i][j][k]=-1;
                }
            }
        }
        return func(0,3,3,cost,cost.length,dp);
    }

    public long func(int i, int prev1, int prev2, int[][] cost, int n,long[][][] dp) {
        if (i == (n - 1) / 2) {
            long ans = Long.MAX_VALUE;
            if (i == n - (i + 1)) {
                for (int j = 0; j < 3; j++) {
                    if (j != prev1 && j != prev2) {
                        ans = Math.min(ans, cost[i][j]);
                    }
                }
            } else {
                for (int j = 0; j < 3; j++) {
                    for (int z = 0; z < 3; z++) {
                        if (j != z && j != prev1 && z != prev2) {
                            ans = Math.min(ans, cost[i][j] + cost[n - (i + 1)][z]);
                        }
                    }
                }
            }
            return dp[i][prev1][prev2]=ans;
        }
        if(dp[i][prev1][prev2]!=-1){
            return dp[i][prev1][prev2];
        }
        long ans = Long.MAX_VALUE;
        for (int j = 0; j < 3; j++) {
            for (int z = 0; z < 3; z++) {
                if (j != z && j != prev1 && z != prev2) {
                    ans = Math.min(ans, cost[i][j] + cost[n - (i + 1)][z] + func(i+1,j,z,cost,n,dp));
                }
            }
        }
        return dp[i][prev1][prev2]=ans;
    }
}
```
['Java']