问题描述
给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。
示例:
输入: [1,2,3,4,5]
输出: [120,60,40,30,24]
问题解决
使用双向动态规划解决
class Solution {
public int[] constructArr(int[] a) {
//使用双向动态规划解决
if(a == null || a.length == 0) return new int[0];
int[] dpLeft = new int[a.length];
int[] dpRight = new int[a.length];
dpLeft[0] = 1;
dpRight[a.length - 1] = 1;
for(int i = 1; i < a.length; i++) {
dpLeft[i] = a[i-1] * dpLeft[i-1];
}
for(int j = a.length - 2; j >= 0; j--) {
dpRight[j] = a[j+1] * dpRight[j+1];
}
for(int i = 0; i < a.length; i++) {
a[i] = dpLeft[i] * dpRight[i];
}
return a;
}
}