题目描述
给定一个数组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]的值可以看作图中的矩阵中每行的乘积。
我们把它分为1的左边和1的右边的乘积称为左三角和右三角
左三角从上到下累乘即可,右三角从下到上累乘。
我的代码:
vector<int> multiply(const vector<int>& A) { int lenth = A.size(); vector<int> B(lenth,1);//注意vector的构造函数,必须要申请空间 for(int i = 1; i < lenth;i++)//上三角 { B[i] = B[i-1]*A[i-1]; } int tmp = 1; for(int i = lenth-2;i >= 0; i--)//下三角并求出一行的乘积 { tmp *= A[i+1]; B[i]*=tmp; } return B; }