您的位置:首页 > 大数据 > 人工智能

"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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: