07斐波那契数列-08跳台阶-09变态跳台阶-10矩阵覆盖

 1 斐波那契数列
 2 //题目:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39
 3 //0、1、1、2、3、5、8、13、21、34、55、89、144、233、377、610、987、1597、2584、4181、6765、10946、17711、28657、46368…
 4 //特别指出:第0项是0,第1项是第一个1。此数列从第2项开始,每一项都等于前两项之和。
 5 class Solution 
 6 {
 7 public:
 8     int Fibonacci(int n) 
 9     {
10         int Init[2] = {0, 1};
11         if (n < 2)
12         {
13             return Init[n];
14         }
15         int FibMinOne = 0;
16         int FibMinTwo = 1;
17         int result;
18         for (int i = 2; i<= n; ++i)
19         {
20             result = FibMinOne + FibMinTwo;
21             FibMinOne = FibMinTwo;
22             FibMinTwo = result;
23         }
24         return result;
25     }
26 };
27 //跳台阶
28 //题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
29 class Solution 
30 {
31 public:
32     int jumpFloor(int number) 
33     {
34         int Init[2] = {1,2};
35         if (number <= 2)
36         {
37             return Init[number-1];
38         }
39         int JumOne = 1;
40         int JumTwo = 2;
41         int result;
42         for (int i = 3; i <= number; ++i)
43         {
44             result = JumOne + JumTwo;
45             JumOne = JumTwo;
46             JumTwo = result;
47         }
48         return result;
49     }
50 };
51 
52 //变态跳台阶
53 //题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
54 //思想:一个台阶,只有一种跳法; 2个台阶,只有2种跳法; 三个台阶,有4种跳法; 四个台阶,有8种跳法;...........
55 class Solution 
56 {
57 public:
58     int jumpFloorII(int number) 
59     {
60         if (number == 1)
61         {
62             return 1;
63         }
64         else
65         {
66             return 2*jumpFloorII(number-1);
67         }
68     }
69 };
70 
71 //矩阵覆盖
72 //题目:我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
73 //思想:当n=1时,有1种方法,当n = 2时有2种方法, 当n = 3时有 3种方法, 当n = 4时 有5种方法.....发现规律 F(n) = F(n-1)+F(n-2);
74 class Solution 
75 {
76 public:
77     int rectCover(int number) 
78     {
79         int Init[2] = {1,2};
80         if (number <= 2)
81         {
82             return Init[number-1];
83         }
84         int rectOne = 1;
85         int rectTwo = 2;
86         int result;
87         for (int i = 3; i <= number; ++i)
88         {
89             result = rectOne+rectTwo;
90             rectOne = rectTwo;
91             rectTwo = result;
92         }
93         return result;
94     }
95 };

 

posted @ 2017-08-20 17:42  繁星的夜空2012  阅读(143)  评论(0)    收藏  举报