脚本宝典收集整理的这篇文章主要介绍了动态规划特辑-01-基础篇,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
目的是通过最后一步,把问题转化成子问题。
递归解法的问题
f(20重复了3次,递归重复了好多次,等到程序的数量特别庞大的时候,就会造成问题。
初始条件就是把最小的情况定义下来,边界情况就是不要数组越界。
从大到小还是从小到大去计算
顺序演示:
正无穷代表拼不出来
最后,可以算出f[27]要用5枚硬币。
计算次数
由于没有重复的计算,相比于递归,动态规划的速度很快。
需要注意的点:
public class Solution {
/**
* @param coins: a list of integer
* @param amount: a total amount of money amount
* @return: the fewest number of coins that you need to make up
*/
public int coinChange(int[] coins, int amount) {
//开多大的数组呢?amount就是总量
//如果要用到n,我们就要开辟数组[n+1],因为下标从0开始
//如果要用到n-1,我们就开辟数组[n]
int[] f = new int[amount + 1];
int n = coins.length;//number of kinds of coins
//inITialization
f[0] = 0;
int i,j;
//f[1] f[2] ... f[27]
for (i = 1; i <= amount; ++i){
f[i] = Integer.MAX_VALUE;
//last coinA[j]
//f[i] = min{f[i-A[0]]+1,...,f[i-A[n-1]]+1]}
for (j = 0; j < n; ++j){
//编程细节的判断,很重要!越界的判断
if (i >= coins[j] && f[i -coins[j]] != Integer.MAX_VALUE){
f[i] = Math.min(f[i - coins[j]]+1, f[i]);
}
}
}
if (f[amount] == Integer.MAX_VALUE){
f[amount] = -1;
}
return f[amount];
}
}
@H_406_179@
如何确定计算顺序呢?根据转移方程来,在算右下角的格子时候,左面的格子刚刚算得到,上面的格子已经得到。
public class Solution {
/**
* @param m: positive integer (1 <= m <= 100)
* @param n: positive integer (1 <= n <= 100)
* @return: An integer
*/
public int uniquePaths(int m, int n) {
//注意此处为什么之开辟m到n,因为最终的结果只用到[m-1,n-1]
int[][] f = new int[m][n];
int i,j;
for (i=0;i<m;i++){//row: top to bottom
for(j=0;j<n;j++){//column: left to right
if(i==0 || j==0){
f[i][j] = 1;
}else{
f[i][j] = f[i-1][j] + f[i][j-1];
}
}
}
return f[m-1][n-1];
}
}
通过最后一步来确定子问题
@H_961_304@
public class Solution {
/**
* @param A: A list of integers
* @return: A boolean
*/
public boolean canJump(int[] A) {
int n = A.length;
boolean[] f = new boolean[n];
f[0] = true;//initialization
for (int j=1;j < n;j++){
f[j] = false; //假设不能通过
//previous stone i
//last jump is From i to j
for (int i=0; i < j; i++){
if(f[i] && i + A[i] >= j){
f[j] = true;
break;
}
}
}
return f[n-1];
}
}
以上是脚本宝典为你收集整理的动态规划特辑-01-基础篇全部内容,希望文章能够帮你解决动态规划特辑-01-基础篇所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。