[WXM] LeetCode 650. 2 Keys Keyboard C++

650. 2 Keys Keyboard

Initially on a notepad only one character ‘A’ is present. You can perform two operations on this notepad for each step:

Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given a number n. You have to get exactly n ‘A’ on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n ‘A’.

Example 1:

Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Note:
- The n will be in the range [1, 1000].

Approach

  1. 题目大意给你一个字母A,然后问你粘贴复制成n个A,需要的最少操作是多少。如果有做了几道递推类型的题,这种就会一下子想到递推的方法,首先n个A最多操作就是一直只复制一个,那么也就操作数为n,有了这个最大值,我们就递推不断优化它的值就好,然后怎么递推呢,只要想怎么可以到达它就好了,只有某个数可以整除n,才可以复制自己m次到达,所以递推方程dp[i]=min(dp[i],dp[j]+i/j)就出来了。
  2. 有两种解法,第一种是通俗的自底向上,还有一种是自顶向下,对于这个问题,自顶向下是比较快的。

Code

自底向上

class Solution {
public:
    int minSteps(int n) {
        vector<int>dp(n + 1);
        dp[1] = 0;
        dp[2]=2;
        for (int i = 3; i <= n; i++) {
            dp[i]=i;
            int c = i / 2;
            for (int j = 2; j <= c; j++) {
                if (i%j==0) {
                    dp[i] = min(dp[i], dp[j] + i / j);
                }
            }
        }
        return dp[n];
    }
};

自顶向下

class Solution {
public:
    int minSteps(int n) {
        if (n == 1)return 0;
        int res = n;
        for (int i = 2; i <= n; i++) {
            if (n%i == 0)
                res = min(res, minSteps(n / i) + i);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/WX_ming/article/details/82114429
今日推荐