href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第692题--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'. Note:The n will be in the range [1, 1000] 思路 分析可知,可以复制一个,然后粘贴n个,胆这样次数太多。要想减少次数,就要复制个数较多(注意复制个数只能越来越多),但复制多了可能会超过。可以发现,若需2n个,可复制n个,需3n个,可复制nge,粘贴2次。而且越早复制越好。这其实就是将n质因数分解。代码7--15行求的li,是用素数筛求小于一个数的所有素数,后面只需将n的所有非1因数加起来即可
show me the code
class Solution(object): def minSteps(self, n): """ :type n: int :rtype: int """ li = [i for i in range(2,1001)] i = 1 while i <len(li): prod =2 * li[i] while prod <=li[-1]: if prod i ''''''n li: li.remove(prod) prod =li[i] i =1 rst = 0 for i in li: if i > n:break ct = 0 while n%i == 0: n/=i ct =1 rst =ct*i return rst

本文介绍LeetCode上第692题——2KeysKeyboard的解题思路及实现方法。通过分析得出,要得到最少操作步骤,关键在于进行有效的复制与粘贴操作,而最优化的方式则是对目标字符数进行质因数分解。

2093

被折叠的 条评论
为什么被折叠?



