If recursion is still the worst time complexity

I have some problems to figure out the worst code complexity below.
(This is not homework, see https://leetcode.com/problems/integer-replacement/description/ .)

int recursion (int n) {
    if (n == 1)
        return 0;
    if (n % 2 == 0) {
        return recursion(n/2) + 1
    } else {
        return min(recursion(n / 2 + 1) + 1, recursion(n - 1)) + 1;
   }
}

The only thing I know is when N == 2 ^ k(k > 0), the worst temporary difficulty O(logN). However, it is unclear when Nnot 2^k. Because it can even number / 2get an odd number anyway. Some said it was still O(logN), but I'm not sure.

I know that code is not the best solution, I just want to analyze the complexity of time. I tried a recursion tree and aggregate analysis doesn't seem to help.

+4
source share
1 answer

n , , T(n) = T(n/2) + 1, n , , T(n) = T(n/2 + 1) + T(n-1) + 1. , n , , n-1 . n/2 + 1 T(n) = T(n/4) + T(n/2) + 3, n/2 + 1 T(n) = 2*T(n/4) + T(n/2) + 3.

T(n) T(n/2) T(n/4) . - , T(n) = O(n^((log(1+sqrt(5))-log(2))/log(2))) ~ O(n^0.69) ( ) T(n) = O(n) ( n/2 + 1 ).

, , .

+4

Source: https://habr.com/ru/post/1689126/


All Articles