首页 > 代码库 > 70.Climbing Stairs(法1递归穷举法2动态规划)
70.Climbing Stairs(法1递归穷举法2动态规划)
You are climbing a stair case. It takes n steps to reachto the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways canyou climb to the top?
HideTags
Dynamic Programming
#pragma once #include<iostream> using namespace std; //法1:递归穷举,超时 int climbStairs1(int n) { if (n == 0) return 1; else if (n < 0) return 0; return climbStairs1(n - 1) + climbStairs1(n - 2); } //法2:动态规划。最后一步可能为1可能为2,即Ai=Ai-1 + Ai-2,斐波那契 int climbStairs2(int n) { if (n < 3) return n; int n1 = 1; int n2 = 2; for (int i = 3; i <= n; i+=2) { n1 = n1 + n2; n2 = n1 + n2;//二步长求斐波那契 } if (n%2) return n1; return n2; } void main() { cout << climbStairs2(6) << endl; cout << climbStairs1(6) << endl; system("pause"); }
70.Climbing Stairs(法1递归穷举法2动态规划)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。