【LeetCode】650. 2 Keys Keyboard 解题报告(Python)

【LeetCode】650. 2 Keys Keyboard 解题报告(Python)

标签: LeetCode


题目地址:https://leetcode.com/problems/2-keys-keyboard/description/

题目描述:

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:

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

题目大意

给定两种操作,复制和粘贴,每次复制只能复制写字板上存在的所有字符,每次粘贴也必须粘贴复制操作得到的所有字符。

给定一个初始的写字板上的字符’A’,问最少经过多少次操作(每次复制/粘贴分别算一次操作),写字板上’A’的个数才能为n。

解题方法

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

大神的解法,从小到大的去试探,尽量用小的数字去除就可以。

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

方法二:

动态规划。待续。

参考:

http://blog.csdn.net/feifeiiong/article/details/76379966(动态规划讲的很详细)
http://blog.csdn.net/MebiuW/article/details/76651618

日期

2018 年 3 月 15 日 –雾霾消散,春光明媚

你可能感兴趣的:(LeetCode,算法)