Solution: As known, this is a simple DP problem. If we can maintain an array dp[] with dp[i] representing the different ways to climb up i steps, we can get the final result in O(N). However, we need O(N) space as well. But actually, since dp[i] = dp[i-1] + dp[i-2] + dp[i-3], we don't need O(N) space, instead, we just need a cache with size 3. Then we can have a space complexity O(1) algorithm:
int climb_stair(int n) { int cache[3]; cache[0] = 1; /*ways to climb 0 step */ cache[1] = 1; /*ways to climb 1 step */ cach2[2] = 2; /*ways to climb 2 steps */ if(n<=2) return cache[n]; for(int i=3; i<=n; i++) { cache[i%3] = cache[0]+cache[1]+cache[2]; } return cache[i%3]; }
Similarly, we can have a O(1) space algorithm for Fibonacci numbers.
Actually, the recurrence relation for Fibonacci numbers has analytical solution, so it can be solved in constant time as well.
ReplyDeleteHi,
ReplyDeletesorry for necroing :) linear recurrences' nth term (such as this one or the Fibonacci etc) can be computed in constant space and *O(logn)* time by iterated matrix powering. Just my 2cents :)
Hi Szaboic,
ReplyDeleteYou are right. Thanks for your comments. Besides, Onur is also right. We even have a constant time solution here. My original post just gave the common solution:)