ITeye博客

计算数组元素的乘积

standalone · 2010-11-03 20:56 · algorithm · 编程语言 · Markdown

Given an array a[i], your task is to generate an array b[i], b[i] is the product of the numbers in the array except the i th number.

 

My solution:

 

DP problem?

 

Define two functions:

f(i)=a[0]*a[1]*a[2]*...*a[i-1]

g(i)=a[i+1]*a[i+2]*...*a[n-1]

So b[i]=f(i)*g(i)

 

Then 

f(0)=1

f(1)=a[0]

f(i+1)=f(i)*a[i]

 

Following this rule we can calculate f[0], f[1],...f[n-1].

 

Similarly, 

g(n-1)=1

g(n-2)=a[n-1]

g(i-1)=g(i)*a[i];

 

Thus we get g[n-1], g[n-2]...g[0] in reverse sequence.

 

At last, we can calculate b[i]=f(i)*g(i).

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。