Rogue Knight Sven

https://www.lintcode.com/problem/rogue-knight-sven/description

public class Solution {
    /**
     * @param n: the max identifier of planet.
     * @param m: gold coins that Sven has.
     * @param limit: the max difference.
     * @param cost: the number of gold coins that reaching the planet j through the portal costs.
     * @return: return the number of ways he can reach the planet n through the portal.
     */
    public long getNumberOfWays(int n, int m, int limit, int[] cost) {
        //
        long[][] dp = new long[n + 1][m + 1];
        dp[0][m] = 1;
        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j <= m; j++) {
                for (int k = i + 1; k - i <= limit && k < dp.length; k++) {
//                    从位置i可以到达的
                    if (j >= cost[k]) {
//                        在i的时候,钱还足够到达
                        dp[k][j - cost[k]] += dp[i][j];
                    }
                }
            }
        }
        long res = 0;
        for (int i = 0; i <= m; i++) {
            res += dp[n][i];
        }
        return res;
    }
}

你可能感兴趣的:(Rogue Knight Sven)