Climbing Stairs

题目

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

思路:

采用递归的思想,最后一次可能是1或者2步,1步只有1种走法,2步可以为1+1和2两种,但是1+1又可以归到1步那里,不用重复计算,所以也是一种走法。故有:f(n) = f(n-1) + f(n-2)

这样问题就转化斐波那契数列的计算了,可以使用递归(leetcode上超时),也可以使用数组存储(空间换时间)。这里我想使用刚刚接触的矩阵快速幂的方法。

f(n) = f(n-1) + f(n-2)   可以转换为

\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}. \begin{pmatrix} f(n-1) \\ f(n-2) \end{pmatrix}= \begin{pmatrix} f(n) \\ f(n-1) \end{pmatrix}

所以对f(n)的计算就可转换为求矩阵\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}的幂,表面上看起来更加复杂了(涉及了矩阵的乘法),但实际上n次方的矩阵只用计算log(n)次,复杂度为O(log(n)).

使用矩阵快速幂的一般步骤为:

1.确定递推式

2.确定矩阵递推式(得到转移矩阵)

3.计算求解

关键步骤在于确定矩阵递推式,有些题目不会明显给出,再看一题。

题目:

 

In our daily life we often use 233 to express our feelings. Actually, we may say 2333, 23333, or 233333 ... in the same meaning. And here is the question: Suppose we have a matrix called 233 matrix. In the first line, it would be 233, 2333, 23333... (it means a0,1 = 233,a0,2 = 2333,a0,3 = 23333...) Besides, in 233 matrix, we got ai,j = ai-1,j +ai,j-1( i,j ≠ 0). Now you have known a1,0,a2,0,...,an,0, could you tell me an,m in the 233 matrix?

There are multiple test cases. Please process till EOF.
For each case, the first line contains two postive integers n,m(n ≤ 10,m ≤ 109). The second line contains n integers, a1,0,a2,0,...,an,0(0 ≤ ai,0 < 231). For each case, output an,m mod 10000007.

一开始我是从行的角度来思考的,每一行的最后一个数的值就等于上一行的所有值的和(每一行的第一个数,因为左边没有数了,就都等于上面的数,也就是第一列的数都是一样的),这样递推关系就很明显了,矩阵递推式也很容易得到,转移矩阵也就是一个下三角矩阵)。但是后来审题的时候发现第一列的会由输入指定(除了第一个),那么这样的思路就无法得到固定的转移矩阵了(每一行的第一个数是不确定的)。

那么就从列的角度来考虑,一列一列地地推到所求的列。先来看第一行,除了第一个数,满足a(n)=a(n-1)*10+3,将第一个数改为23,就都满足这一关系了。再来考虑每一列的其余的值a_{i,j},因为a_{i,j} = a_{i-1,j} +a_{i,j-1},所以a_{i,j}=a_{0,j}+a_{1,j-1}+a_{2,j-1}+...+a_{i,j-1},转移矩阵也就会包含一个下三角矩阵,即:

\begin{pmatrix} 10 & 0 & 0 & 0 & \cdots & 0 & 1\\ 10 & 1 & 0 & 0 & \cdots & 0 & 1\\ 10 & 1 & 1 & 0 & \cdots & 0 & 1\\ 10 & 1 & 1 & 1& \cdots & 0 & 1\\ & & \hdots \\ 10 & 1 & 1 & 1& \cdots & 1 & 1\\ 0 & 0 & 0 & 0& \cdots & 0 & 1\\ \end{pmatrix}. \begin{pmatrix} a_0 \\ a_1 \\ a_2 \\ \vdots \\ a_n\\ 3 \end{pmatrix}= \begin{pmatrix} a_0^' \\ a_1^' \\ a_2^' \\ \vdots \\ a_n^'\\ 3 \end{pmatrix}

a_i表示第一列的第i个数,通过递推可以得到剩余的列,这样一来问题就解决了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值