什么是动态规划
Dynamic programming, like the divide-and-conquer method, solves problems by combining the solutions to subproblems.
在Introduction to algorithms中,书里提到
When developing a dynamic-programming algorithm, we follow a sequence of four steps:
- Characterize the structure of an optimal solution.
- Recursively define the value of an optimal solution.
- Compute the value of an optimal solution, typically in a bottom-up fashion.
- Construct an optimal solution from computed information.
爬楼梯问题
最开始的时候,我不懂的这个题跟斐波那契数列有什么关系,经过在纸上操作了几个例子之后发现:
因为我们每次只能爬2或者1阶楼梯,那么我们就在(n-1)和(n-2)处做文章。在(n-1)的位置上,我们再爬1阶就能到n,有多少种方法能爬到n-1,便是有多少种方法能通过只爬一阶楼梯到n。同理,在(n-2)的位置上,只要知道有多少种方法到(n-2)的位置,我们即可知道有多少种方法爬2阶楼梯到n。综上所述,爬到(n-1)的所有方法的数量+爬到(n-2)的所有的方法的数量,则为爬到n阶楼梯的方法的数量。
在这个例子中,我们发现了爬n阶楼梯的方法的数量跟爬(n-1)和(n-2)阶楼梯的数量的关系,这就是个把大问题分解成小问题的很好的例子。通过把(n-1)和(n-2)的情况combine在一起,我们conquer了这个大问题。
public int climbStairs(int n) {
int[] dp = new int[n + 1]; //创建DP数组
dp[1] = 1; //爬一阶楼梯只有一种方法
dp[2] = 2;//爬两阶楼梯有两种方法,第一阶开始爬1节,或者从第0阶开始爬2节
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}