算法复习:递归
一、斐波那契数列
面试题10- II. 青蛙跳台阶问题 同 509. 斐波那契数
#define mods 1000000007 class Solution { public: map<int,int>donser; int find(int n) { if(n==0||n==1) return 1; if(donser[n]!=0) donser[n]; else donser[n]=(find(n-1)+find(n-2))%mods; return donser[n]; } int numWays(int n) { donser[0]=1; donser[1]=1; find(n); return donser[n]; } };
这次青蛙可以跳的步数从0到N都可以
class Solution { public: map<int,int>donser; int find(int n) { if(n==0||n==1) return 1; if(donser[n]!=0) return donser[n]; else { for(int i=0;i<n;i++) { donser[n]+=find(i); } } return donser[n]; } int jumpFloorII(int number) { donser[0]=1; donser[1]=1; find(number); return donser[number]; } };
二、正则匹配
leedcode 10. 正则表达式匹配
递归解法,时间复杂度比较高,后面要尝试改成动规
bool end_or_not(string p) { for(int i=0;i<p.size();i+=2) { if(((p[i]>='a'&&p[i]<='z')||p[i]=='.')&&p[i+1]=='*') continue; return false; } return true; } bool check(string s, string p) { int donser[27]; memset(donser,0,sizeof(donser)); for(int i=0;i<p.size();i++) { if(p[i]=='.'||p[i]=='*') continue; if(donser[p[i]-'a']==0) { donser[p[i]-'a']=1; int lable=0; if(p[i+1]=='*') continue; for(int j=0;j<s.size();j++) { if(s[j]==p[i]) { lable=1; break; } } if(lable==0) return false; } } return true; } class Solution { public: bool isMatch(string s, string p) { int ptr_s=0,ptr_p=0; bool x=0; char now=p[ptr_p],next=p[ptr_p+1]; if(check(s,p)==false) return false; if(s[ptr_s]=='\0') { return end_or_not(p.substr(ptr_p,p.size()-ptr_p)); } if(p[ptr_p]=='\0') return false; if((now>='a'&&now<='z'&&next!='*')||(now=='.'&&next!='*')) { if(s[ptr_s]==p[ptr_p]&&s[ptr_s+1]=='\0'&&p[ptr_p+1]=='\0') return true; if(s[ptr_s]==p[ptr_p]||(now=='.'&&next!='*')) { ptr_s++; ptr_p++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_s--; ptr_p--; if(x==true) return true; } else { return false; } } if(now=='.'&&next=='*') { ptr_p+=2; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; if(x==true) return true; ptr_s++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_s--; if(x==true) return true; } if(now>='a'&&now<='z'&&next=='*') { if(s[ptr_s]!=p[ptr_p]) { ptr_p+=2; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; if(x==true) return true; } else { ptr_p+=2; ptr_s++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; ptr_s--; if(x==true) return true; ptr_s++; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_s--; if(x==true) return true; ptr_p+=2; x=isMatch(s.substr(ptr_s,s.size()-ptr_s),p.substr(ptr_p,p.size()-ptr_p)); ptr_p-=2; if(x==true) return true; } } return false; } };