1.利用二维数组求解硬币组合问题
private static long countWays_2(int n) {
int[] coins = {1,5,10,25};
//二维数组的方式
long[][] dp = new long[7][n+1];
for (int i = 1; i <=n; i++) {
dp[0][i] = 0;//用0种硬币凑成i元的组合数为0
}
for (int i = 0; i < coins.length; i++) {
dp[i][0] = 1;//用i种硬币凑成0元的组合数为1
}
for (int i = 1; i <= coins.length; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j]= 0;
for (int k = 0; k <=j/coins[i-1]; k++) {
dp[i][j] += dp[i-1][j-k*coins[i-1]];
//dp[i][sum] = dp[i-1][sum - 0*Vm] + ... + dp[i-1][sum - K*Vm]; 其中K = sum / Vm
}
}
}
return dp[coins.length][n];
}
2.利用一维数组求解硬币组合问题
private static int countWays(int n) {
int[] coins = {1,5,10,25};
//一维数组
int[] dp = new int[100001];//默认为0
dp[0] = 1;
int len1 = coins.length;
for (int i = 0; i < len1; i++) {
for (int j = coins[i]; j <= n; j++) {
//二级循环从大到小
dp[j] = (dp[j]+dp[j-coins[i]])%100000007;
}
}
for (int i = 0; i < dp.length; i++) {
if(dp[i]!=0)
System.out.print(dp[i]+" ");
}
System.out.println();
return dp[n];
}
注:何时使用一维数组和二维数组求解动态规划问题可以参考:
http://blog.csdn.net/tbwood/article/details/22747215