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