1538. 卡牌游戏 II
你跟你的朋友在玩一个卡牌游戏,总共有 n
张牌。每张牌的成本为 cost[i]
并且可以对对手造成 damage[i]
的伤害。你总共有 totalMoney
元并且需要造成至少 totalDamage
的伤害才能获胜。每张牌只能使用一次,判断你是否可以取得胜利。
样例
input:
cost = [1,2,3,4,5]
damage = [1,2,3,4,5]
totalMoney = 10
totalDamage = 10
output:
true
典型的01背包问题 物品的重量和价值对应本题里的成本和伤害
public boolean cardGame(int[] cost, int[] damage, int totalMoney, int totalDamage) {
int n = cost.length;
if (n == 0 || totalMoney == 0)
return false;
int[][] memo = new int[n][totalMoney + 1];
for (int j = 0; j <= totalMoney; j++)
memo[0][j] = (j >= cost[0] ? damage[0] : 0);
for (int i = 1; i < n; i++)
for (int j = 0; j <= totalMoney; j++) {
memo[i][j] = memo[i - 1][j];
if (j >= cost[i])
memo[i][j] = Math.max(memo[i][j], damage[i] + memo[i - 1][j - cost[i]]);
}
return memo[n - 1][totalMoney] >= totalDamage;
}