"Factorial Trailing Zeroes" and "Pascal's Triangle II"

来源:互联网 发布:有内涵的小说 知乎 编辑:程序博客网 时间:2024/06/08 08:42

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;    }};


0 0