/* 爬楼梯问题:每次可以跨上1…M个台阶,一共有N个台阶,问从最底下爬到最高处有几种爬法 */ #include <stdio.h> #define MAX 100 /* 共n个台阶,每次最多m个台阶,f[i]保存爬n个台阶的爬法总数,返回f[n] * 优化版O(n) */ long long PaLouTi(const int n, const int m, long long * const f) { int i; f[0] = f[1] = 1; for (i = 2; i <= m; ++ i) f[i] = f[i - 1] * 2; for (i = m + 1; i <= n; ++ i) f[i] = f[i - 1] * 2 - f[i - m - 1]; return f[n]; } /* 共n个台阶,每次最多m个台阶,f[i]保存爬n个台阶的爬法总数,返回f[n] * 原版O(n^2) */ long long PaLouTi2(const int n, const int m, long long * const f) { int i, j, max1; f[0] = 1; for (i = 1; i <= n; ++ i) for (f[i] = 0, max1 = i - m > 0 ? i - m : 0, j = i - 1; j >= max1; -- j) f[i] += f[j]; return f[n]; } int main() { long long f[MAX]; int M, N; while (printf("M, N : "), scanf("%d %d", &M, &N) == 2) { printf("%I64d %I64d/n", PaLouTi(N, M, f), PaLouTi2(N, M, f)); } return 0; } f[n] = f[n <= m ? 1 : n - m] + ... + f[n - 1] PS:如有问题请留言,谢谢。