我对这个SO帖子有一个问题:了解嵌套循环将运行多少次
其中,嵌套循环的 3 个通用公式是:n(n+1)(n+2)/3。我真的不知道为什么第二个内循环运行 n+1 次,而外循环运行 n 次(内循环在退出 for 循环之前不会再次运行一次吗?无论哪种方式...一般公式为
n(n+1)(n+2)...(n+r-1)
---------------------
r!
这里,r 是嵌套循环的数量。
我想知道这个公式对于嵌套循环是否总是相同的,或者它是否根据 for 循环内的比较而变化......如果它基于比较,那么如果在考试中给我一些不同的 for 循环,我如何确定公式?如果 for 循环的比较与创建该公式的 SO 帖子中的比较不同,我如何生成或提出此公式?
你必须训练你的大脑来识别和遵循执行中的模式,并为特定情况提出一个公式。一般的经验法则是,如果一个for
循环将运行其中的代码x
次,并且它内部有一个将运行y
次的循环,那么内部循环中的代码将运行x*y
次。
最常见的for
循环类型从零开始,递增 1,直到达到某个数字,如下所示:
for(int i = 0; i < x; i++)
for(int j = 0; j < y; j++)
for(int k = 0; k < z; k++)
// code here runs x * y * z times
为了回答您的问题,如果您更改任何for
循环的任何部分,它将更改内部代码的执行次数。您需要通过考虑逻辑代码执行来确定这将是多少次。
for(int i = 1; i < x; i++)
for(int j = 0; j < y * 2; j++)
for(int k = 0; k < z; k += 2)
// code here runs (x - 1) * (y * 2) * (z / 2) times
在上面的示例中,每个for
循环都以不同的方式进行调整。请注意,运行次数的总体公式几乎保持不变,但现在每个循环每次被命中时都会运行不同的次数。
当循环的变量影响多个循环时,事情会变得更加复杂。
for(int i = 0; i < x; i++)
for(int j = i; j < y; j++) // notice how `j` starts as `i`
// Code here runs `y` times the first time through the outer loop,
// then `y - 1` times,
// then `y - 2` times,
// ...
// if x < y, the pattern continues until the xth time,
// when this loop runs `y - x` times.
// if x > y, the pattern will stop when y == x, and
// code here will run 0 times for the remainder of
// the loops.
所以在最后一个示例中,假设x < y
,循环将运行y + (y-1) + (y-2) ... + (y-x)
次。
它根据内在值而变化。例。
for (int i = 0; i < 100; i++)
{
//this loop will run 100 times.
for (int i1 = 0; i1 < 100; i++)
{
// This will run 100 times every outer loop int.
// This means that for each index i in the outer loop this will run 100 times.
// The outer loop runs 100 time and this runs 10,000 times in total.
}
}
for (int i = 0; i < 100; i++)
{
//this loop will run 100 times.
for (int i1 = 0; i1 < 10; i++)
{
// This will run 10 times every outer loop int.
// This means that for each index i in the outer loop this will run 10 times.
// The outer loop runs 100 time and this runs 1,000 times in total.
}
}
一个更简单的看待它的方法可能是这个。
for (int i = 0; i < 10; i++)
{
//this loop will run 10 times.
Console.WriteLine("int i = " + i.ToString()");
for (int i1 = 0; i1 < 10; i++)
{
// This will run 10 times every outer loop int.
// This means that for each index i in the outer loop this will run 10 times.
// The outer loop runs 10 time and this runs 100 times.
Console.WriteLine("int i2 = " + i2.ToString()");
}
}
这将输出这个。
int i = 0
int i2 = 0
int i2 = 1
int i2 = 2
int i2 = 3
int i2 = 4
int i2 = 5
int i2 = 6
int i2 = 7
int i2 = 8
int i2 = 9
int i = 1
int i2 = 0
int i2 = 1
int i2 = 2
int i2 = 3
int i2 = 4
int i2 = 5
int i2 = 6
int i2 = 7
int i2 = 8
int i2 = 9
等等。
该公式基于内部循环编号。(循环结束时打开。