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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MebiuW/article/details/76651618

这道题可以转化成,给一个数字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)

猜你喜欢

转载自blog.csdn.net/MebiuW/article/details/76651618