"Factorial Trailing Zeroes" and "Pascal's Triangle II"
2016-06-05 09:48
417 查看
Factorial Trailing Zeroes:
找从1到n之间所有数包含多少个约数5.
class Solution {
public:
int trailingZeroes(int n) {
int res = 0;
while(n)
{
res += n/5;
n /= 5;
}
return res;
}
};
Pascal's Triangle II:
题目要求空间复杂度是O(n),一开始没想出来。后来发现杨辉三角是一行比一行长的,最后一行一定是最长的一行,所以可以用最后一行的空间计算,每次只计算一行的值,前一行的前一行的值丢弃就好了,这样一次次迭代计算就能求出指定行的所有值。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> tmp(rowIndex+1,0);
auto it = tmp.begin();
*it=1;
for(int ocnt = 0;ocnt<rowIndex;ocnt++)
{
for(int icnt = 0;icnt<ocnt;icnt++)
{
tmp[icnt] = tmp[icnt]+tmp[icnt+1];
}
tmp.insert(tmp.begin(),1);
tmp.erase(tmp.end()-1);
}
return tmp;
}
};
找从1到n之间所有数包含多少个约数5.
class Solution {
public:
int trailingZeroes(int n) {
int res = 0;
while(n)
{
res += n/5;
n /= 5;
}
return res;
}
};
Pascal's Triangle II:
题目要求空间复杂度是O(n),一开始没想出来。后来发现杨辉三角是一行比一行长的,最后一行一定是最长的一行,所以可以用最后一行的空间计算,每次只计算一行的值,前一行的前一行的值丢弃就好了,这样一次次迭代计算就能求出指定行的所有值。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> tmp(rowIndex+1,0);
auto it = tmp.begin();
*it=1;
for(int ocnt = 0;ocnt<rowIndex;ocnt++)
{
for(int icnt = 0;icnt<ocnt;icnt++)
{
tmp[icnt] = tmp[icnt]+tmp[icnt+1];
}
tmp.insert(tmp.begin(),1);
tmp.erase(tmp.end()-1);
}
return tmp;
}
};
相关文章推荐
- 第25课:基于MAT分析Shallow Heap和Retained Heap
- 正则表达式--抓取email地址
- 【杭电】[1302]The Snail
- 论文笔记之:Attention For Fine-Grained Categorization
- Mac升级到EI Captain之后pip install 无法使用问题
- 游戏编程中的人工智能-遗传算法入门(五)
- 217. Contains Duplicate
- 1285:Combinations, Once Again
- 【Leetcode】Climbing Stairs
- AIDL简单实现(2)
- AIDL简单实现(1)
- kafka集群启动遇到LeaderNotAvailableException错误
- UVA253——骰子涂色(Cube painting)
- POJ1804 Brainman (逆序对)
- 使用行为树(Behavior Tree)实现游戏AI
- Failed to lookup view... in views directory...
- Communications link failure
- git 首次使用以及error: failed to push some refs to ****问题的解决
- 内置的材质包含文件 .cginc
- UVA 10780 Again Prime? No Time(质因数分解)