基础的动态规划
原理
动态规划的思想的是把一个问题分解为规模小一点的同样的问题,然后找出小规模的问题和大规模问题的联系,从而递归地得出大规模问题的解。
实现方法
1.记忆化搜索(递归的思想)
从动态规划的思想上理解,通过搜索的方式,将大问题分解为小参数的性质相同的问题,但是一些不同参数的大问题可能会包含一些相同参数的小问题,对于这些小问题,我们搜索两次太费时间,搜索完一次后,就将结果存下来,这就是所谓的记忆化搜索。
2.递推关系式
就是直接列出大问题和小问题的联系,然后从小规模问题出发,组合小规模的问题得出大规模的问题。
3.例子
两种形式是等价的,比如最简单的求斐波那契数列。
//看这是从大规模的问题n开始入手的。记忆化搜索。
dp[n+1]
int f(int n){
if(有保存的结果) return dp[n];
return f(n-1)+f(n-2);
}
//这是从小规模(i=3)问题开始逐渐往上推的。
for(int i=3;i<n;i++)
dp[i]=dp[i-1]+dp[i-2];
步骤
- 边界条件
- 递推关系式
有关计数的动态规划问题
重集的组合问题,比如经典的找钱问题,用多种面值的钞票,凑一个数额的钱,每种钞票都有充分多张。
POJ 2229
Description
Farmer John commanded his cows to search for different sets of numbers that sum to a given number. The cows use only numbers that are an integer power of 2. Here are the possible sets of numbers that sum to 7:
- 1+1+1+1+1+1+1
- 1+1+1+1+1+2
- 1+1+1+2+2
- 1+1+1+4
- 1+2+2+2
- 1+2+4
Help FJ count all possible representations for a given integer N (1 <= N <= 1,000,000).
Input
A single line with a single integer, N.
Output
The number of ways to represent N as the indicated sum. Due to the potential huge size of this number, print only last 9 digits (in base 10 representation).
解题思路
首先看题意,是想用 2 , 4 , 8 , 16 … 2 i 2,4,8,16…2^i 2,4,8,16…2i这样的数凑一个整数。有多少种凑法。
错误的思路
是不是可以定义sum[n]为凑成整数n的方式的个数。
自然想到 s u m [ n ] = s u m [ n − 1 ] + s u m [ n − 2 ] + s u m [ n − 4 ] + … + s u m [ n − 2 i ] sum[n]=sum[n-1]+sum[n-2]+sum[n-4]+…&#