容易:通过迭代法求解T(n)= T(n-1)+ n

时间:2012-12-02 22:40:43

标签: algorithm iteration

有人可以帮帮我吗?

  

使用迭代方法解决它。 T(n)= T(n-1)+ n

非常感谢步骤说明。

5 个答案:

答案 0 :(得分:29)

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

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

T(n-2) = T(n-3) + n-2

等等 你可以用T(n)代替T(n-1)和T(n-2)的值来得到模式的一般概念。

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


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

T(n) = T(n-k) +kn - k(k-1)/2

对于基本情况:

n - k =1 so we can get T(1)

k = n - 1 在上面替换

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

您可以看到的是订单n ^ 2

答案 1 :(得分:8)

展开它!

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

等等,直到

T(n) = 1 + 2 + ... + n = n(n+1)/2   [= O(n^2)]

提供T(1) = 1

答案 2 :(得分:1)

在使用迭代的伪代码中:

function T(n) {
    int result = 0;

    for (i in 1 ... n) {
       result = result + i;
    }

    return result;
}    

答案 3 :(得分:1)

另一种更简单的解决方案

T(n) = T(n-1) + n
     = T(n-2) + n-1 + n
     = T(n-3) + n-2 + n-1 + n
     // we can now generalize to k
     = T(n-k) + n-k-1 + n-k-2 + ... + n-1 + n
     // since n-k = 1 so k = n-1 and T(1) = 1
     = 1 + 2 + ... + n
     = n(n-1)/2
     = n^2/2 - n/2
     // we take the dominating term which is n^2*1/2 therefor 1/2 = big O
     = big O(n^2)

答案 4 :(得分:-2)

简易方法:

T (n) = T (n - 1) + (n )-----------(1)
 //now submit T(n-1)=t(n)

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

now submit (2) in (1) you will get
i.e T(n)=[T(n-2)+n-1]+(n)
T(n)=T(n-2)+2n-1 //simplified--------------(3)

 now, T(n-2)=t(n)
T(n-2)=T((n-2)-2)+[2(n-2)-1]
  T(n-2)=T(n-4)+2n-5---------------(4)
  now submit (4) in (2) you will get
   i.e T(n)=[T(n-4)+2n-5]+(2n-1)
  T(n)=T(n-4)+4n-6 //simplified
    ............
 T(n)=T(n-k)+kn-6
  **Based on General form T(n)=T(n-k)+k, **
  now, assume n-k=1 we know T(1)=1
            k=n-1

    T(n)=T(n-(n-1))+(n-1)n-6
    T(n)=T(1)+n^2-n-10
   According to the complexity 6 is constant

         So , Finally O(n^2)