zoukankan      html  css  js  c++  java
  • 跳台阶问题(递归分治)

    题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

    分析:递归做或者直接嵌套循环

     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 int ans=0;
     5 /*int f(int n){//递归算法,效率低!!!
     6     if(n==0) return 0;
     7     if(n<=2) return n;
     8     return f(n-1)+f(n-2); 
     9 }*/
    10 
    11 int f(int n){/*嵌套循环*/
    12     if(n==0) return 0;
    13     if(n==1) return 1;
    14     int a=1,b=1;
    15     int sum=0;
    16     for( int i=2; i<=n; i++ ){
    17         sum=a+b;
    18         a=b;
    19         b=sum;
    20     }
    21     return sum;
    22 }
    23 
    24 int main(int argc, char const *argv[])
    25 {
    26     int n;
    27     cin>>n;
    28     ans=f(n);
    29     cout<<ans<<endl;
    30     return 0;
    31 }

      拓展:变态跳台阶问题

     
    题目:一个台阶总共有n级,如果一次可以跳1级,也可以跳2级......它也可以跳上n级。此时该青蛙跳上一个n级的台阶总共有多少种跳法?
     
    分析:用f(n)表示青蛙跳上n阶台阶的跳法数,设定f(0) = 1;
    当n = 1 时,只有一种跳的方式,一阶跳,f(1) = 1
    当n = 2 时,有两种跳的方式,一阶跳和两阶跳,f(2) = f(1) + f(0) = 2
    当n = 3 时,有三种跳的方式,第一次跳出一阶后,后面还有f(3-1)中跳法; 第一次跳出二阶后,后面还有f(3-2)中跳法;第一次跳出三阶后,后面还有f(3-3)中跳法,f(3) = f(2) + f(1) + f(0) = 4
    当n = n 时,第一次跳出一阶后,后面还有f(n-1)中跳法; 第一次跳出二阶后,后面还有f(n-2)中跳法......第一次跳出n阶后,后面还有 f(n-n)中跳法,即:
    f(n) = f(n-1) + f(n-2) + f(n-3) + ... + f(n-n)+1 =1+ f(0) + f(1) + f(2) + ... + f(n-1)
    又因为 f(n-1) =1+ f(0) + f(2) + f(3) + ... + f(n-2)
    两式相减得:f(n) = 2 * f(n-1)    ( n >= 2)
                     |  0,n = 0
    f(n)   =       |  1, n = 1
                     |  2 * f(n-1) , n >= 2
     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 int ans=0;
     5 // int f(int n){//递归算法,效率低!!!
     6 //     if(n==0) return 0;
     7 //     if(n==1) return 1;
     8 //     return f(n-1)*2; 
     9 // }
    10 
    11 int f(int n){/*嵌套循环*/
    12     if(n==0) return 0;
    13     if(n==1) return 1;
    14     int sum=1;
    15     for( int i=2; i<=n; i++ ){
    16         sum=2*sum;
    17     }
    18     return sum;
    19 }
    20 
    21 int main(int argc, char const *argv[])
    22 {
    23     int n;
    24     cin>>n;
    25     ans=f(n);
    26     cout<<ans<<endl;
    27     return 0;
    28 }
    有些目标看似很遥远,但只要付出足够多的努力,这一切总有可能实现!
  • 相关阅读:
    [JSOI2007][BZOJ1031] 字符加密Cipher|后缀数组
    leetcode Flatten Binary Tree to Linked List
    leetcode Pascal's Triangle
    leetcode Triangle
    leetcode Valid Palindrome
    leetcode Word Ladder
    leetcode Longest Consecutive Sequence
    leetcode Sum Root to Leaf Numbers
    leetcode Clone Graph
    leetcode Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/Bravewtz/p/10471064.html
Copyright © 2011-2022 走看看