简体   繁体   English

如何解决:T(n)= T(n - 1)+ n

[英]How to solve: T(n) = T(n - 1) + n

I have the following worked out: 我得到以下结论:

T(n) = T(n - 1) + n = O(n^2)

Now when I work this out I find that the bound is very loose. 现在,当我解决这个问题时,我发现边界非常宽松。 Have I done something wrong or is it just that way? 我做错了什么或是这样吗?

You need also a base case for your recurrence relation. 您还需要一个基于重复关系的基础案例。

T(1) = c
T(n) = T(n-1) + n

To solve this, you can first guess a solution and then prove it works using induction. 要解决这个问题,您可以先猜测一个解决方案,然后使用归纳法证明它是有效的。

T(n) = (n + 1) * n / 2 + c - 1

First the base case. 首先是基础案例。 When n = 1 this gives c as required. 当n = 1时,根据需要给出c。

For other n: 对于其他n:

  T(n)
= (n + 1) * n / 2 + c - 1
= ((n - 1) + 2) * n / 2 + c - 1
= ((n - 1) * n / 2) + (2 * n / 2) + c - 1
= (n * (n - 1) / 2) + c - 1) + (2 * n / 2)
= T(n - 1) + n

So the solution works. 所以解决方案有效。

To get the guess in the first place, notice that your recurrence relationship generates the triangular numbers when c = 1: 要获得猜测,请注意当c = 1时,您的递归关系会生成三角形数字

T(1) = 1:

*

T(2) = 3:

*
**

T(3) = 6:

*
**
***

T(4) = 10:

*
**
***
****

etc..

Intuitively a triangle is roughly half of a square, and in Big-O notation the constants can be ignored so O(n^2) is the expected result. 直观地,三角形大约是正方形的一半,并且在Big-O表示法中,常数可以被忽略,因此O(n ^ 2)是预期的结果。

Think of it this way: 想一想:
In each "iteration" of the recursion you do O(n) work. 在递归的每次“迭代”中,您执行O(n)工作。
Each iteration has n-1 work to do, until n = base case. 每次迭代都有n-1个工作要做,直到n =基本情况。 (I'm assuming base case is O(n) work) (我假设基本情况是O(n)工作)
Therefore, assuming the base case is a constant independant of n, there are O(n) iterations of the recursion. 因此,假设基本情况是n的常量独立,则存在递归的O(n)次迭代。
If you have n iterations of O(n) work each, O(n)*O(n) = O(n^2). 如果每次都有n次迭代的O(n)工作,则O(n)* O(n)= O(n ^ 2)。
Your analysis is correct. 你的分析是正确的。 If you'd like more info on this way of solving recursions, look into Recursion Trees. 如果您想了解有关这种求解递归的更多信息,请查看递归树。 They are very intuitive compared to the other methods. 与其他方法相比,它们非常直观。

The solution is pretty easy for this one. 这个解决方案非常简单。 You have to unroll the recursion: 您必须展开递归:

T(n) = T(n-1) + n = T(n-2) + (n - 1) + n = 
= T(n-3) + (n-2) + (n-1) + n = ... =
= T(0) + 1 + 2 + ... + (n-1) + n 

You have arithmetic progression here and the sum is 1/2*n*(n-1) . 你在这里有算术级数,总和是1/2*n*(n-1) Technically you are missing the boundary condition here, but with any constant boundary condition you see that the recursion is O(n^2) . 从技术上讲,这里缺少边界条件,但是在任何常量边界条件下,您会看到递归为O(n^2)

Looks about right, but will depend on the base case T(1). 看起来是正确的,但将取决于基本情况T(1)。 Assuming you will do n steps to get T(n) to T(0) and each time the n term is anywhere between 0 and n for an average of n/2 so n * n/2 = (n^2)/2 = O(n^2). 假设您将执行n步骤以使T(n)变为T(0)并且每次n项在0和n之间的任何位置,平均为n / 2,因此n * n / 2 =(n ^ 2)/ 2 = O(n ^ 2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM