将题目等价到青蛙跳台阶,类似于斐波那契数列。
动态规划的两种写法
public class Solution { public int RectCover(int target) { if(target<1) return 0; if(target ==1||target ==2) return target; int first =1; int second =2; int result = 0; for(int i=3;i<=target;i++){ result = first + second; first = second; second = result; } return result; } }
使用数组,空间复杂度稍高
public class Solution { public int RectCover(int target) { int[] arr = new int[target+1];//为了防止越界 return fib(target,arr); } public int fib(int target,int[] arr){ if(target==0) return arr[0]=0; if(target==1) return arr[1]=1; if(target==2) return arr[2]=2; arr[1] =1; arr[2] =2; for(int i=3;i<=target;i++){ arr[i] = arr[i-1]+arr[i-2]; } return arr[target]; } }