Leetcode 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].

思路

這道題可以轉化成,給一個數字N,只允許你有兩種操作:
1、複製 (複製只能複製完notepad上所有的字符)
2 、粘貼
每個操作各算一次。
問,如何用最少的次數得到N
舉例:
如果 N = 1,則相當於不用操作,因爲notepad上初始化就有1個A字符。
如果 N = 2,要生成AA,則需要複製,粘貼各一次,此時output爲2。
如果 N = 3,要生成AAA,則複製1次A,然後粘貼2次A;此時output爲3。
如果 N = 4,要生成AAAA,有2種方法:
1.複製1次A,然後粘貼1次A, 再複製1次AA再粘貼1次AA,此時output爲4。
ii.複製1次A,連續粘貼3次A,此時output也爲4。

動態規劃狀態

dp[n]表示生成n個字符所需的最小操作次數
dp[0, .. , n]初始爲∞
dp[0] = dp[1] = 0

按照大腦的線性思考方式,我們對n個A string(n>1)的substring做遍歷判斷dp數組值,所有一共是(2 + n+1)n/2次,時間複雜度爲O(n^2)

狀態轉移方程

dp[x] = min(dp[x], dp[y] + x / y) ,y ∈[1, x) 並且 x % y == 0

python實現

class Solution(object):
    def minSteps(self, n):
        """
        :type n: int
        :rtype: int
        """
        dp = [0x7FFFFFFF] * (n + 1)
        dp[0] = dp[1] = 0
        for x in range(2, n + 1):
            for y in range(1, x):
                if x % y == 0:
                    dp[x] = min(dp[x], dp[y] + x / y)
        return dp[n]

AC Runtime: 1072 ms

C++實現

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

AC Runtime: 73 ms
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章