组合数的递归调用:poj 1942 Paths on a Grid
2015-02-05 17:36
295 查看
题目大意:
一个矩形网格grid(n*m),从左下角走到右上角,问所有可能的路径数目。
解题思路:
以3×4的网格为例,问题等价于从_ _ _ _ _ _ _选出4个空格为“→”,剩下3个空格为“↑”,例如:
→ → → → ↑ ↑ ↑
→
↑ →
↑ → ↑ →
… … … …
!!!组合数C(n+m,m)
为了减少计算,这里m取min{n,m}
C(n,m)=A(n,m)/A(m,m)=n! / (n-m)!×m!
关于组合数C(n,m)的代码实现,这里提供两种方法:
(1)递归调用
(2)迭代(自己复合自己,重叠一定的步骤,新的值替代旧的值,累加、累乘都属于迭代过程)
参考代码+部分解释:
递归调用
==========================华丽的分割线=============================
迭代
一个矩形网格grid(n*m),从左下角走到右上角,问所有可能的路径数目。
解题思路:
以3×4的网格为例,问题等价于从_ _ _ _ _ _ _选出4个空格为“→”,剩下3个空格为“↑”,例如:
→ → → → ↑ ↑ ↑
→
↑ →
↑ → ↑ →
… … … …
!!!组合数C(n+m,m)
为了减少计算,这里m取min{n,m}
C(n,m)=A(n,m)/A(m,m)=n! / (n-m)!×m!
关于组合数C(n,m)的代码实现,这里提供两种方法:
(1)递归调用
(2)迭代(自己复合自己,重叠一定的步骤,新的值替代旧的值,累加、累乘都属于迭代过程)
参考代码+部分解释:
递归调用
#include #include #include #include #include #include #include using namespace std; typedef long long ll; const int maxn = 7e4+10; ll n,m; ll com(ll n,ll m)//返回C(n,m) { return m==0?1:com(n-1,m-1)*n/m; } int main() { // freopen("input.txt","r",stdin); while(cin>>n>>m&&(n||m)){ ll a=n+m,b=min(n,m); cout<
==========================华丽的分割线=============================
迭代
#include #include #include #include #include #include #include using namespace std; typedef long long ll; const int maxn = 7e4+10; ll n,m; ll solve(ll n,ll m)//返回C(n,m) { ll ans=1; for(ll i=n,j=1;j<=m;i--,j++)//C(n,m)=A(n,m)/A(m,m); ans=ans*i/j; //不要写成ans*=i/j,这样就先运算i/j了 return ans; } int main() { // freopen("input.txt","r",stdin); while(cin>>n>>m&&(n||m)){ ll a=n+m,b=min(n,m); cout<
相关文章推荐
- poj 1942 Paths on a Grid (求组合数)
- POJ 1942 Paths on a Grid 组合数的应用 (计算路径总个数)
- POJ 1942 Paths on a Grid(组合数)
- POJ-1942 Paths on a Grid 组合数
- poj 1942 Paths on a Grid(组合数学--组合数)
- POJ-1942 Paths on a Grid 组合数
- Paths on a Grid POJ 1942 组合数学
- POJ 1942 Paths on a Grid
- POJ 1942 Paths on a Grid
- poj 1942 Paths on a Grid
- POJ 1942 Paths on a Grid
- POJ 1942 Paths on a Grid
- POJ 1942 Paths on a Grid
- [ACM] POJ 1942 Paths on a Grid (组合)
- POJ1942 Paths on a Grid(组合)
- POJ 1942 Paths on a Grid
- POJ 1942 Paths on a Grid
- POJ 1942 Paths on a Grid
- poj 1942 Paths on a Grid
- poj 1942 Paths on a Grid