运行 ❯
获取您的
自己的
网站
×
更改方向
更改主题,深色/浅色
前往 Spaces
Python
C
Java
def F(n): if memo[n] != None: # Already computed return memo[n] else: # Computation needed print('Computing F('+str(n)+')') if n <= 1: memo[n] = n else: memo[n] = F(n - 1) + F(n - 2) return memo[n] memo = [None]*7 print('F(6) = ',F(6)) print('memo = ',memo) #Python
#include <stdio.h> #include <stdlib.h> int memo[7]; char computed[7] = {0}; // Tracks whether the value has been computed int F(int n) { if (computed[n]) { // Already computed return memo[n]; } else { // Computation needed printf("Computing F(%d)\n", n); if (n <= 1) { memo[n] = n; computed[n] = 1; // Mark as computed } else { memo[n] = F(n - 1) + F(n - 2); computed[n] = 1; // Mark as computed } return memo[n]; } } int main() { printf("F(6) = %d\n", F(6)); printf("memo = ["); for (int i = 0; i < 7; i++) { if (i > 0) { printf(", "); } if (computed[i]) { printf("%d", memo[i]); } else { printf("None"); } } printf("]\n"); return 0; } //C
public class Main { private static Integer[] memo = new Integer[7]; // Use Integer to allow null values public static void main(String[] args) { System.out.println("F(6) = " + F(6)); System.out.print("memo = ["); for (int i = 0; i < memo.length; i++) { if (i != 0) { System.out.print(", "); } System.out.print(memo[i]); } System.out.println("]"); } public static int F(int n) { if (memo[n] != null) { // Already computed return memo[n]; } else { // Computation needed System.out.println("Computing F(" + n + ")"); if (n <= 1) { memo[n] = n; } else { memo[n] = F(n - 1) + F(n - 2); } return memo[n]; } } } //Java
Python 结果
C 结果
Java 结果
计算 F(6)
计算 F(5)
计算 F(4)
计算 F(3)
计算 F(2)
计算 F(1)
计算 F(0)
F(6) = 8
memo = [0, 1, 1, 2, 3, 5, 8]
计算 F(6)
计算 F(5)
计算 F(4)
计算 F(3)
计算 F(2)
计算 F(1)
计算 F(0)
F(6) = 8
memo = [0, 1, 1, 2, 3, 5, 8]
计算 F(6)
计算 F(5)
计算 F(4)
计算 F(3)
计算 F(2)
计算 F(1)
计算 F(0)
F(6) = 8
memo = [0, 1, 1, 2, 3, 5, 8]