https://oj.leetcode.com/problems/unique-paths/

首先,转换成一个排列组合问题,计算组合数C(m+n-2) (m-1),请自动想象成上下标。

class Solution {
public:
int uniquePaths(int m, int n) {
if(m == && n == )
return ;
int sum1 = ;
int sum2 = ;
for(int i = ; i <= m-; i++)
sum1 *= i;
for(int j = m+n-; j >= n; j--)
sum2 = sum2*j;
return sum2/sum1;
}
};

runtime error,当测试数据是36,7的时候,也就是说,这个数太大了,已经算不了了。

于是参考了discuss

class Solution {
public:
int uniquePaths(int m, int n) {
if(m == && n == )
return ;
int sum1 = ;
int sum2 = ;
//exchange;
int temp;
if(m<n)
{
temp = n; n = m; m = temp;
}
int p,q;
int commonFactor;
for(int i = ; i<= n-; i++)
{
p = i;
q = i+m-;
commonFactor = gcd(p,q);
sum1 = sum1 * (p/commonFactor);
sum2 = sum2 * (q/commonFactor);
commonFactor = gcd(sum1,sum2);
sum1 = sum1/commonFactor;
sum2 = sum2/commonFactor;
} return sum2/sum1;
} int gcd(int a, int b)
{
while(b)
{
int c = a%b;
a = b;
b = c;
}
return a;
}
};

输入58,61的时候wa,因为结果得了个负数,明显又溢出了。

于是:

#include <iostream>
using namespace std; class Solution {
public:
int uniquePaths(int m, int n) {
if(m == && n == )
return ;
long long sum1 = ;
long long sum2 = ;
//exchange;
int temp;
if(m<n)
{
temp = n; n = m; m = temp;
}
int p,q;
int commonFactor;
for(int i = ; i<= n-; i++)
{
p = i;
q = i+m-;
commonFactor = gcd(p,q);
sum1 = sum1 * (p/commonFactor);
sum2 = sum2 * (q/commonFactor);
commonFactor = gcd(sum1,sum2);
sum1 = sum1/commonFactor;
sum2 = sum2/commonFactor;
} return sum2/sum1;
} int gcd(long long a, long long b)
{
while(b)
{
int c = a%b;
a = b;
b = c;
}
return a;
}
}; int main()
{
Solution myS;
cout<<myS.uniquePaths(,);
return ;
}

中间过程中使用了long long 类型。

记住求公约数的算法。

最新文章

  1. C# Lamada表达式
  2. 浅谈JavaScript中的apply,call和bind
  3. c#基础学习汇总----------base和this,new和virtual
  4. hdu 4605-Magic Ball Game(树状数组)
  5. 如何制作windows服务安装包
  6. 使用Python把Gtest XML测试结果转换为HTML格式
  7. ZOJ 3879 Capture the Flag 15年浙江省赛K题
  8. ASP.NET获取客户端信息,获取客户端IP等等
  9. Xshell连接虚拟机VMware
  10. Oracle的用户、角色以及权限相关操作
  11. JavaWeb 后端 &lt;十二&gt; 之 过滤器 filter 乱码、不缓存、脏话、标记、自动登录、全站压缩过滤器
  12. 用Docker解决坑爹的环境搭建系列——PHP+Apache2
  13. MySQL 笔记整理(5) --深入浅出索引(下)
  14. three.js使用base64 图片创建Texture纹理
  15. js 中 (function($){...})(jQuery) 含义
  16. linux下编译tex,bib成pdf文件
  17. Callable的用法示例
  18. 华为交换机配置NTP服务端/客户端
  19. erc721-165学习
  20. [No0000E5]C# 运算符

热门文章

  1. 【模拟】HHHOJ#251. 「NOIP模拟赛 伍」高精度
  2. hash 哈希查找复杂度为什么这么低?
  3. pandas关联mysql并读写数据库
  4. python爬虫用到的一些东西
  5. 【jenkins】jenkins执行nohup java报错
  6. SimpleDateFormat优化写法
  7. Ubuntu系统里的python
  8. LeetCode(303)Range Sum Query - Immutable
  9. 原生Ajax+springBoot实现用户登录
  10. selenium2中的TestNg注解和数据驱动的简介及使用