package leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode.com/problems/dice-roll-simulation/
 */
public class Problem1223 {
    public int dieSimulator(int n, int[] rollMax) {
        return dieSimulator(n, rollMax, new HashMap<>());
    }

    private static int dieSimulator(int n, int[] rollMax, Map<String, Integer> memo) {
        if (n == 0) {
            return 1;
        }
        String key = n + "," + Arrays.toString(rollMax);
        if (memo.containsKey(key)) {
            return memo.get(key);
        }
        int count = 0;
        for (int i = 1; i <= 6; i++) {
            if (rollMax[i - 1] > 0) {
                rollMax[i - 1]--;
                count += dieSimulator(n - 1, rollMax, memo);
                rollMax[i - 1]++;
            }
        }
        memo.put(key, count);
        return count;
    }

    public static void main(String[] args) {
        Problem1223 prob = new Problem1223();
//        System.out.println(prob.dieSimulator(2, new int[]{1,1,2,2,2,3})); // 34
//        System.out.println(prob.dieSimulator(2, new int[]{1,1,1,1,1,1})); // 30
        System.out.println(prob.dieSimulator(3, new int[]{1,1,1,2,2,3})); // 181
//        System.out.println(prob.dieSimulator(1, new int[]{1,1,1,1,1,1})); // 6
    }
}

package leetcode;

/**
 * https://leetcode.com/problems/dice-roll-simulation/
 */
public class Problem1223 {
    public int dieSimulator(int n, int[] rollMax) {
        int[][][] memo = new int[5000][6][16];
        return dieSimulator(n, rollMax, -1, 0, memo);
    }

    private static int dieSimulator(int n, int[] rollMax, int last, int currentLength,
                                    int[][][] memo) {
        if (n == 0) {
            return 1;
        }
        if (last >= 0 && memo[n][last][currentLength] > 0) {
            return memo[n][last][currentLength];
        }
        int count = 0;
        for (int i = 0; i < 6; i++) {
            if (i == last && currentLength == rollMax[i]) {
                continue;
            }
            count = (count + dieSimulator(n - 1, rollMax, i, i == last ? currentLength + 1 : 1, memo)) % 1_000_000_007;
        }
        if (last >= 0) {
            memo[n][last][currentLength] = count;
        }
        return count;
    }
}

Solve problem 1223