Leetcode 397:整数替换

题目描述

给定一个正整数 n,你可以做如下操作:

1. 如果 n 是偶数,则用 n / 2替换 n。
2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。
n 变为 1 所需的最小替换次数是多少?

示例 1:

输入:
8

输出:
3

解释:
8 -> 4 -> 2 -> 1
示例 2:

输入:
7

输出:
4

解释:
7 -> 8 -> 4 -> 2 -> 1

7 -> 6 -> 3 -> 2 -> 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-replacement
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

class Solution {
public:
    unordered_map<int,int> dp;
    int integerReplacement(int n) {
        if(n==1 || n==INT_MAX) return (n==1)?0:32;
        if(dp[n]!=0) return dp[n];
        int tmp;
        if(n%2==0) tmp=1+integerReplacement(n/2);
        else tmp=1+min(integerReplacement(n-1),integerReplacement(n+1));
        dp[n]=tmp;
        return tmp;
    }
};

为什么这样dp超时呢。。。

class Solution {
public:
    int integerReplacement(int n) {
        if(n==1) return 0;
        unordered_map<int,int> dp;
        dp[0]=0;
        dp[1]=0;
        for(int i=2;i<=n;++i){
            if(i%2==0) dp[i]=dp[i/2]+1;
            else dp[i]=min(dp[(i-1)/2],dp[(i+1)/2])+2;
        }
        return dp[n];
    }
};
发布了584 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_35338624/article/details/104080547