暴力递归搜索:
static int violenceRecursion( int n ) {
if( n <= 2 ) {
return n < 1 ? 1 : n ;
}
return violenceRecursion( n - 1 ) + violenceRecursion( n - 2 );
}
int jumpFloor( int number ) {
return violenceRecursion( number );
}
记忆化递归搜索:
static int memoryRecursion( int n,int buf[] ) {
if( n <= 2 ) {
return n < 1 ? 1 : n;
}
if( buf[n - 1] < 1 ) {
buf[n - 1] = memoryRecursion( n - 1, buf );
}
if( buf[n - 2] < 1 ) {
buf[n - 2] = memoryRecursion( n - 2, buf );
}
return (buf[n - 1] + buf[n - 2]);
}
int jumpFloor( int number ) {
int buf[12345] = {0};
return memoryRecursion( number, buf );
}
空间复杂度O(N)的动态规划:
int jumpFloor( int number ) {
int answer = 0, i = 0, *dp = NULL;
if( number < 3 ) {
return number;
}
dp = (int *)malloc( (number) * sizeof(*dp) );
dp[0] = 1; // 第一个台阶只能选择跳1个台阶.
dp[1] = 2; // 第二个台阶可以选择跳1或2个台阶.
for( i = 2; i < number; ++i ) {
dp[i] = dp[i - 1] + dp[i - 2]; // 跳1个台阶 和 跳2个台阶的总和.
}
answer = dp[number - 1];
free( dp );
return answer;
}
空间复杂度O(1)的动态规划:
int jumpFloor( int number ) {
int i = 0, n1 = 1, n2 = 2, n3 = 0;
if( number < 3 ) {
return number;
}
for( i = 3; i <= number; ++i ) {
n3 = n1 + n2; // 跳1个台阶 和 跳2个台阶的总和.
n1 = n2;
n2 = n3;
}
return n3;
}
空间复杂度O(1)的动态规划,超简洁代码,跟计算 Fibonacci 的第n项一样:
int jumpFloor( int number ) {
int a[3] = {0,1,2};
if( number < 3 ) {
return a[number];
}
while( number-- >= 3 ) {
a[0] = a[1];
a[1] = a[2];
a[2] = a[0] + a[1];
}
return a[2];
}