Leetcode 650. 2 Keys Keyboard 2指键盘 解题报告

这道题可以转化成,给一个数字N,初始K=1,C=0然后只允许你有两种操作:
1、K = K + C (paste)
2 、C = K (copy all)
问,如何操作可以使得最快的得到N

N>1时,其实这道题就是将N分解为M个数字的乘积,且M个数字的和最小。

比如:
2 = 1 * 1 = 2
3 = 1 * 1 *1 = 3
4 = 2 * 2 = 1* 1* 1 *1 =4
等等
那么最快的讲一个数分解为N个质数的和怎们办呢

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

给了两个方法,第一个是看别人的写的,第二个是我自己做的,速度似乎差不多

第一个主要是从小到大的去试探,尽量用小的数字去除就可以

大神简洁解法:39ms

class Solution(object):
    def minSteps(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = 0
        for i in range(2, n+1):
            while (n % i == 0):
                res += i
                n /= i
        return res

DP 递归 版 36ms

首先转化为两个数字的子问题,且A=B*C 且 B+C最小,就是指这两个数字的和最小(其实就是从B=sqrt(A),不断向下试探)找,然后对于这两个数字再进行递归。。记得加cache(不然就用字典,提前好到所有1000内的质数,这个更快):

class Solution(object):
    import math
    def helper(self, n):

        """
        :type n: int
        :rtype: int
        """
        if n in self.cache:
            return self.cache[n]
        for i in range(int(math.sqrt(n)),1,-1):
            if n % i == 0:
                a = self.helper(i)
                b = self.helper(n / i)
                self.cache[n] = a + b
                return a+ b
        self.cache[n] = n
        return n


    def minSteps(self, n):
        """
        :type n: int
        :rtype: int
        """
        self.cache = dict()
        self.cache[1] = 1
        if n == 1:
            return 0
        return self.helper(n)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值