70.爬楼梯
题目链接
根据递推公式写一个快速幂,矩阵形式如下
当然递推公式也可以写成解析形式的解,有兴趣可以了解下线性齐次递推式的解
class Solution {
typedef long long LL;
public:
struct Mat{
LL a[2][2];
Mat(){memset(a,0,sizeof a);};
Mat(LL q){memset(a,0,sizeof a);for(int i = 0;i < 2; i++)a[i][i] = q;}
Mat operator * (const Mat &B){
Mat C;
for(int i = 0; i < 2; i++){
for(int k = 0 ;k < 2; k++){
if(!a[i][k])continue;
for(int j = 0; j < 2; j++){
C.a[i][j] += a[i][k] * B.a[k][j];
}
}
}
return C;
}
Mat operator ^ (int p){
Mat ans(1);
Mat A = *this;
while(p){
if(p&1)ans = ans * A;
p >>= 1;
A = A * A;
}
return ans;
}
};
int climbStairs(int n) {
if(n==0||n==1)return 1;
Mat A;A.a[0][0] = A.a[0][1] = A.a[1][0] = 1;
A = A ^ (n-1);
return A.a[0][0] + A.a[0][1];
}
};
83.删除排序链表中的重复元素
题目链接
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode *st = head;
while(st!=NULL&&st->next!=NULL){
if(st->val==st->next->val)st->next = st->next->next;
else st = st -> next;
}
return head;
}
};