P1044 栈
P1044 栈
题解
记忆化搜索了解一下???
代码
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<string> #include<cstring> #include<cstdlib> #include<queue> using namespace std; inline int read() { int ans=0; char last=' ',ch=getchar(); while(ch<'0'||ch>'9') last=ch,ch=getchar(); while(ch>='0'&&ch<='9') ans=ans*10+ch-'0',ch=getchar(); if(last=='-') ans=-ans; return ans; } int n; int f[20][20]; int dfs(int x,int y) //待操作序列里面还有x个数字,已经有y个数字入栈 { if(f[x][y]!=0) return f[x][y]; //记忆化过了 if(x==0) return 1; //没有待操作数字了,只能全部弹出栈里的数字 f[x][y]+=dfs(x-1,y+1); //考虑新数字入栈 if(y>0) f[x][y]+=dfs(x,y-1); //考虑栈顶出栈 return f[x][y]; } int main() { n=read(); printf("%d",dfs(n,0)); return 0; }
DP也了解一下??
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<string> #include<cstring> #include<cstdlib> #include<queue> using namespace std; inline int read() { int ans=0; char last=' ',ch=getchar(); while(ch<'0'||ch>'9') last=ch,ch=getchar(); while(ch>='0'&&ch<='9') ans=ans*10+ch-'0',ch=getchar(); if(last=='-') ans=-ans; return ans; } int n; int f[20][20]; int main() { n=read(); for(int i=1;i<=n;i++) f[0][i]=1; for(int i=1;i<=n;i++) for(int j=i;j<=n;j++) { if(i==j) f[i][j]=f[i-1][j]; else f[i][j]=f[i][j-1]+f[i-1][j]; } printf("%d",f[n][n]); return 0; }