一个人每次只能走一层楼梯或者两层楼梯,问走到第n层楼梯一共有多少种方法
利用动态规划实现如下:
#include <iostream> using namespace std; const int MAX = 100; int result[MAX]; int fib_time(int n) { int res; if (result[n]>0) //若大于零,说明该子问题原来已经求过解 return result[n]; //直接返回对应的数组元素 if (n == 0 || n == 1) res = 1; else res = fib_time(n - 1) + fib_time(n - 2); result[n] = res; //每次都将求过解的子问题赋给对应数组元素 return res; } int main() { int i = 0; int n = 0; cout << "Please input the number of Stairs:" << endl; cin >> n; for (i = 0; i <= n; i++) { result[i] = -1; } cout << "The differ_way_number is:"<<endl<<fib_time(n) << endl;; return 0; }
测试:
原文地址:https://www.cnblogs.com/khnl/p/11639454.html
时间: 2024-11-09 02:53:12