|
| 1 | +// Source : https://leetcode.com/problems/integer-replacement/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2016-11-04 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * |
| 7 | + * Given a positive integer n and you can do operations as follow: |
| 8 | + * |
| 9 | + * If n is even, replace n with n/2. |
| 10 | + * If n is odd, you can replace n with either n + 1 or n - 1. |
| 11 | + * |
| 12 | + * What is the minimum number of replacements needed for n to become 1? |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * |
| 16 | + * Input: |
| 17 | + * 8 |
| 18 | + * |
| 19 | + * Output: |
| 20 | + * 3 |
| 21 | + * |
| 22 | + * Explanation: |
| 23 | + * 8 -> 4 -> 2 -> 1 |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * |
| 27 | + * Input: |
| 28 | + * 7 |
| 29 | + * |
| 30 | + * Output: |
| 31 | + * 4 |
| 32 | + * |
| 33 | + * Explanation: |
| 34 | + * 7 -> 8 -> 4 -> 2 -> 1 |
| 35 | + * or |
| 36 | + * 7 -> 6 -> 3 -> 2 -> 1 |
| 37 | + ***************************************************************************************/ |
| 38 | + |
| 39 | +class Solution { |
| 40 | +public: |
| 41 | + |
| 42 | + |
| 43 | + int integerReplacement_recursion(int n) { |
| 44 | + if ( n <= 1) return 0; // recursive exited point |
| 45 | + if ( n == INT_MAX ) return 32; // special case to avoid integer overflow. |
| 46 | + if ( n % 2 == 0 ) return integerReplacement(n/2) + 1; |
| 47 | + return min( integerReplacement(n+1), integerReplacement(n-1) ) + 1; |
| 48 | + } |
| 49 | + |
| 50 | + int integerReplacement_recursionWithCache(int n) { |
| 51 | + static unordered_map<int, int> cache; |
| 52 | + //if hitted the cache, just return the result |
| 53 | + if (cache.find(n) != cache.end()) return cache[n]; |
| 54 | + |
| 55 | + int result; |
| 56 | + if ( n <= 1) return 0; // recursive exited point |
| 57 | + if ( n == INT_MAX ) return 32; // special case to avoid integer overflow. |
| 58 | + if ( n % 2 == 0 ) result = integerReplacement(n/2) + 1; |
| 59 | + else result = min( integerReplacement(n+1), integerReplacement(n-1) ) + 1; |
| 60 | + |
| 61 | + //add into cache |
| 62 | + cache[n] = result; |
| 63 | + return result; |
| 64 | + } |
| 65 | + |
| 66 | + int integerReplacement(int n) { |
| 67 | + return integerReplacement_recursionWithCache(n); |
| 68 | + } |
| 69 | +}; |
0 commit comments