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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值