构建乘积数组 (from牛客)

构建乘积数组

题目:给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。

解题思路:先算下三角中的连乘,即我们先算出B[i]中的一部分,然后倒过来按上三角中的分布规律,把另一部分也乘进去。

构建乘积数组 (from牛客)_第1张图片

代码:

class Solution {
public:
    vector multiply(const vector& A) {
        vector res;
        res.push_back(1);
        for(int i=1;i=0;i--)
        {
             tmp*=A[i+1];
             res[i]*=tmp;
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode)