九章算法 | 微软面试题:流浪剑客斯温

2021-02-03 17:54:23 +08:00
 hakunamatata11

描述

在物质位面“现实”中,有 n+1 个星球,分别为星球 0,星球 1,……,星球 n 。

每一个星球都有一个传送门,通过传送门可以直接到达目标星球而不经过其他的星球。

不过传送门有两个缺点。

第一,从星球 i 通过传送门只能到达编号比 i 大,且与 i 的差不超过 limit 的星球。

第二,通过传送门到达星球 j,需要 cost[j]个金币。

现在,流浪剑客斯温到达星球 0 后身上有 m 个金币,请问他有多少种方法通过传送门到达星球 n ?

在线评测地址

样例 1

比如 n = 15, 返回一个字符串数组:

输入:
n = 1
m = 1, 
limit = 1
cost = [0, 1]
输出:
1
解释:
方案 1:星球 0→星球 1

样例 2

输入:
n = 1
m = 1
limit = 1
cost = [0,2]
输出:
0
解释:
无合法方案

算法:dp

我们用 dp[i][j]dp[i][j]代表从星球 00 出发到达星球 ii 后拥有 jj 个金币的方案数。

复杂度分析

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];
        for (int i = 0; i < m; i++) {
            dp[0][i] = 0;
        }
        dp[0][m] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                dp[i][j] = 0;
                for (int t = Math.max(0, i - limit); t <= i - 1; t++) {
                    if (j + cost[i] <= m) {
                        dp[i][j] += dp[t][j + cost[i]];
                    }
                }
            }
        }
        long ans = 0;
        for (int i = 0; i <= m; i++) {
            ans += dp[n][i];
        }
        return ans;
    }
}

更多题解参考

477 次点击
所在节点    推广
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/751024

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX