Title Description
Given an array A [0,1, ..., n- 1], please construct an array B [0,1, ..., n- 1], where B is the element B [i] = A [ 0] * A [1] * ... * A [i-1] * A [i + 1] * ... * A [n-1]. You can not use the division .
Analysis: Note that the subject of the request can not be used division!
We found that if action is taken to violence, then there will be a lot of repetitive operations, we can use an array of records to reduce repetitive operation
Using a two-dimensional array to record the product and dp, dp representatives [i] [j] to the index i of the product of the index j , after the calculation may be recorded, so that when later need no longer required to calculate, it can be directly used, this is the so-called memorandum of law
First of dp array initialization
dp[0][0]=a[0]
dp[0][i]=dp[0][i-1]*a[i],i>=1,i<n
dp[n-1][n-1]=a[n-1]
dp[i][n-1]=dp[i+1][n-1]*a[i]
State transition formula:
When i == 0, b [i] = dp [1] [n-1], a separate header processing unit
When when i == n-1, b [i] = dp [0] [i-1], the tail alone treatment
i>0&&i<n-1时,b[i]=dp[0][i-1]*dp[i+1][n-1]
Time complexity: O (N)
Space complexity: O (N * N)
class Solution { public : Vector < int > Multiply ( const Vector < int > & A) { int n-= a.size (); int [n-] DP [n-]; // DP [i] [J]: The index i the product of the element index j Memset (DP, 0 , the sizeof ( 0 )); Vector < int > B (n-, 0 ); // initialize DP [ 0 ] [ 0 ] = a [ 0 ]; for ( int= I . 1 ; I <n-; I ++ ) { DP [ 0 ] [I] DP = [ 0 ] [I- . 1 ] * A [I]; } DP [n- - . 1 ] [N- . 1 ] = A [n- - . 1 ]; for ( int I = N- 2 ; I> = 0 ; i-- ) { DP [I] [n- - . 1 ] DP = [I + . 1 ] [N- . 1 ] * A [I]; } // need to handle a separate header and trailer for ( int I = 0; i<n; i++) { if(i==0) { b[i]=dp[1][n-1]; } else if(i==n-1) { b[i]=dp[0][i-1]; } else { b[i]=dp[0][i-1]*dp[i+1][n-1]; } } return b; } };