题目:
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步那里,不用重复计算,所以也是一种走法。故有:
这样问题就转化斐波那契数列的计算了,可以使用递归(leetcode上超时),也可以使用数组存储(空间换时间)。这里我想使用刚刚接触的矩阵快速幂的方法。
可以转换为
所以对的计算就可转换为求矩阵的幂,表面上看起来更加复杂了(涉及了矩阵的乘法),但实际上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.
一开始我是从行的角度来思考的,每一行的最后一个数的值就等于上一行的所有值的和(每一行的第一个数,因为左边没有数了,就都等于上面的数,也就是第一列的数都是一样的),这样递推关系就很明显了,矩阵递推式也很容易得到,转移矩阵也就是一个下三角矩阵)。但是后来审题的时候发现第一列的会由输入指定(除了第一个),那么这样的思路就无法得到固定的转移矩阵了(每一行的第一个数是不确定的)。
那么就从列的角度来考虑,一列一列地地推到所求的列。先来看第一行,除了第一个数,满足,将第一个数改为23,就都满足这一关系了。再来考虑每一列的其余的值,因为,所以,转移矩阵也就会包含一个下三角矩阵,即:
表示第一列的第i个数,通过递推可以得到剩余的列,这样一来问题就解决了。