构建乘积数组

题目:给定一个数组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]。不能使用除法。

思路:基于动态规划,先求i-1个和后n-i个乘积,保存之后求B[i]

 public int[] multiply(int[] A) {
        if(A==null||A.length==0)
            return new int[1];
        int[] B=new int[A.length];
        int t1=1;
        int[] t2=new int [A.length];
        t2[A.length-1]=1;
        for(int i=1;i<A.length;i++)
            t2[A.length-i-1]=t2[A.length-i]*A[A.length-i];
        
       for (int i = 0; i < A.length; i++) {
            if(i!=0){
                t1 *=A[i-1];
            }
            B[i] = t1 * t2[i];
        }
    return B;    
    }
原文地址:https://www.cnblogs.com/team42/p/6691782.html