***Leetcode 650. 2 Keys Keyboard

https://leetcode.com/problems/2-keys-keyboard/description/

非常好的medium的题

这里有个证明 https://leetcode.com/problems/2-keys-keyboard/discuss/105900/C++-O(sqrt(n))-DP-and-greedy-prime-number-solution

里面a + b <= ab 稍微解释下:

1/b + 1/a <=1 而 a>=2 b>=2 所以成立

class Solution {
public:
    int minSteps(int n) {
        if (n == 1) return 0;
        vector<int> dp(n+1, 0);
        // dp[1] = 1;
        dp[2] = 2;
        return dfs(dp, n);
    }
    int dfs(vector<int>&dp, int x) {
        if (dp[x] ) return dp[x];
        int ans = x;
        for (int i = 2; i <= sqrt(x); i++) {
            if (x % i == 0) {
                ans = min( ans, dfs(dp, x/i) + i );
                ans = min( ans, dfs(dp, i) + x/i );
            }
        }
        dp[x] = ans;
        return dp[x];
    }
};

更好的还是

class Solution {
public:
    int minSteps(int n) {
        int ans = 0;
        for (int i = 2; i <= int(sqrt(n)); i++) {
            while (n % i == 0) {
                n /= i;
                ans += i;
            }
        }
        
        if (n > 1) {
            ans += n;
        }
        return ans;
    }
};






猜你喜欢

转载自blog.csdn.net/u011026968/article/details/79890311
今日推荐