public class Solution { public int Fib(int N) { if (N == 0) { return 0; } else if (N == 1) { return 1; } else { List<int> list = new List<int>(); list.Add(0); list.Add(1); for (int i = 2; i <= N; i++) { list.Add(list[i - 1] + list[i - 2]); } return list[N]; } } }
补充一个python的实现:
1 class Solution: 2 def fib(self, N: int) -> int: 3 if N==0: 4 return 0 5 if N==1: 6 return 1 7 dp = [0] * (N+1) 8 dp[0] = 0 9 dp[1] = 1 10 for i in range(2,N+1): 11 dp[i] = dp[i-1] + dp[i-2] 12 return dp[N]