1. 程式人生 > >Leetcode:397.整數替換

Leetcode:397.整數替換

給定一個正整數 n,你可以做如下操作:

1. 如果 是偶數,則用 n / 2替換 n
2. 如果 是奇數,則可以用 n + 1n - 1替換 n
變為 1 所需的最小替換次數是多少?

示例 1:

輸入:
8

輸出:
3

解釋:
8 -> 4 -> 2 -> 1

示例 2:

輸入:
7

輸出:
4

解釋:
7 -> 8 -> 4 -> 2 -> 1
或
7 -> 6 -> 3 -> 2 -> 1

解題思路:

動態規劃,遞迴。假設dp[n]為數字n轉換成1的次數,特殊地dp[1]=1。根據題意,我們可以得到如下的遞推關係:

  • 當n是奇數時,dp[n]=min(dp[n+1],dp[n-1])+1.
  • 當n是偶數時,dp[n]=dp[n/2]+1.

注意,奇數如果寫這個遞推,而n卻是int型別,那麼n+1可能是會溢位整數的,因此這個寫法不好。由於n+1必然是偶數,那麼可以做如下改進:

  • 當n是奇數時,dp[n] = min(dp[(n>>1)+1]+1,dp[n-1])+1。

這樣一來就避免了溢位的現象。

另外,本題遞迴存在多條路徑,存在重複訪問同一個n的情況,為了避免重複遞迴的現象,將之前遞迴過的數值儲存在雜湊表中,利用unordered_map<int,int>即可。這樣一來演算法就幾乎完美了。

C++程式碼
class Solution {
public:
    int integerReplacement(int n) {
        if (mp[n] > 0) return mp[n];
        else mp.erase(n);
        if (n == 1) return 0;
        if ((n & 1) == 0) { 
            int num1=integerReplacement(n >> 1) + 1; 
            mp[n] = num1;
            return num1;
        }
        int add = integerReplacement((n >> 1) + 1) + 2;
        int del = integerReplacement(n - 1) + 1;
        int small= min(add, del);
        mp[n] = small;
        return small;
    }
    unordered_map<int, int> mp;
};