有n个信封,包含n封信,现在把信拿出来,再装回去,要求每封信不能装回它原来的信封,问有多少种装法?
给定一个整数n,请返回装发个数,为了防止溢出,请返回结果Mod 1000000007的值。保证n的大小小于等于300。
int countWays(int n) {
// write code here
if(n<2)return 0;
if(n==2)return 1;
return (n-1)*(countWays(n-1)%1000000007+countWays(n-2)%1000000007);
} int countWays(int n) {
// write code here
int a=0;
int b=1;
if(n<=1)return a;
if(n==2)return b;
long result;
long x=0;
long y=1;
for(int i=3;i<=n;i++)
{
result=(i-1)*(x+y)%1000000007;
x=y;
y=result;
}
return result;
} 这样就很好了,根据n的大小,从头到尾计算一遍,直至f(n)。原文:http://blog.csdn.net/yutianxin123/article/details/52085753