注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
最近复习动态规划的时候发现一个问题,有的时候动态规划数组声明是m+1,有的时候是m, 什么时候声明m, 什么时候声明m+1呢? 谢谢大家
举个例子
Coin change 2 这个就是声明m+1
[color=rgba(0, 0, 0, 0.65)]You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
[color=rgba(0, 0, 0, 0.65)]
[color=rgba(0, 0, 0, 0.650980392156863)]public class Solution {
[color=rgba(0, 0, 0, 0.650980392156863)] /**
[color=rgba(0, 0, 0, 0.650980392156863)] * @param amount: a total amount of money amount. 1point 3acres
[color=rgba(0, 0, 0, 0.650980392156863)] * @param coins: the denomination of each coin
[color=rgba(0, 0, 0, 0.650980392156863)] * @return: the number of combinations that make up the amount
[color=rgba(0, 0, 0, 0.650980392156863)] */
[color=rgba(0, 0, 0, 0.650980392156863)] public int change(int amount, int[] coins) {. Waral dи,
[color=rgba(0, 0, 0, 0.650980392156863)] // write your code here
[color=rgba(0, 0, 0, 0.650980392156863)] int[] dp = new int[amount + 1];
[color=rgba(0, 0, 0, 0.650980392156863)] dp[0] = 1;. 1point 3acres
[color=rgba(0, 0, 0, 0.650980392156863)] for (int i = 0; i < coins.length; i++) {
[color=rgba(0, 0, 0, 0.650980392156863)] for (int j = coins[i]; j <= amount; j++) {
[color=rgba(0, 0, 0, 0.650980392156863)] dp[j] += dp[j - coins[i]];
[color=rgba(0, 0, 0, 0.650980392156863)] }-baidu 1point3acres
[color=rgba(0, 0, 0, 0.650980392156863)] }
[color=rgba(0, 0, 0, 0.650980392156863)] return dp[amount];
[color=rgba(0, 0, 0, 0.650980392156863)] }
[color=rgba(0, 0, 0, 0.650980392156863)]}
[color=rgba(0, 0, 0, 0.650980392156863)]
. ----
Unique Paths 这个就是声明m
. 1point3acres.com
. .и
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for(int i = 0; i<n; i++){
dp[0][i] = 1;
}
for(int i =0; i<m; i++){
dp[i][0] = 1;
}
for(int i=1; i<m; i++){. Waral dи,
for(int j=1; j<n; j++){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];.1point3acres
}
}. 1point3acres.com
|