Easy: Solve T(n)=T(n-1)+n by Iteration Method

前端 未结 5 2226
灰色年华
灰色年华 2021-02-19 19:59

Can someone please help me with this ?

Use iteration method to solve it. T(n) = T(n-1) +n

Explanation of steps

相关标签:
5条回答
  • 2021-02-19 20:37

    Expand it!

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

    and so on, until

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

    provided that T(1) = 1

    0 讨论(0)
  • 2021-02-19 20:57

    In pseudo code using iteration:

    function T(n) {
        int result = 0;
    
        for (i in 1 ... n) {
           result = result + i;
        }
    
        return result;
    }    
    
    0 讨论(0)
  • 2021-02-19 20:59

    Another solution:

    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 T(1) = 1
         = 1 + 2 + ... + n    //Here 
         = 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)
    
    0 讨论(0)
  • 2021-02-19 21:01
    T(n) = T(n-1) + n
    
    T(n-1) = T(n-2) + n-1
    
    T(n-2) = T(n-3) + n-2
    

    and so on you can substitute the value of T(n-1) and T(n-2) in T(n) to get a general idea of the pattern.

    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    ...(1)
    

    For base case:

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

    => k = n - 1
    substitute in (1)

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

    Which you can see is of Order n2 => O(n2).

    0 讨论(0)
  • 2021-02-19 21:01

    Easy Method:

    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)
    
    0 讨论(0)
提交回复
热议问题