2

我在阅读一篇有很多公式的文章时遇到了麻烦。它有几个总结(我的意思是这样的:∑h ∑i)我可以把它写成两个嵌套的for循环吗?

喜欢:

for (h=1; h<=5; h++){
    for(i=1; i<=5; i++){
        sum+=i;
    }
}

谢谢你的耐心 :)

4

1 回答 1

1

如果您在这里查看示例 11 :

 Sum(Sum(x*y)) = Sum(x)*Sum(y)

左边可以写成嵌套的for循环:

for(x goes 1 to n)
  for(y goes 1 to m)
    add to the result (x*y)

右边可以写成两个独立的循环。

for(x goes 1 to n)
  add to the firstResult (x)
for(y goes 1 to m)
  add to the secondResult (y)
set result to firstResult * secondResult

右侧提高了 O(n*m) 与 O(n+m) 的时间效率,但需要一些空间(保留第一个和第二个结果)。

于 2012-06-26T13:35:21.510 回答