Leetcode 650. 2 Keys Keyboard
来源:互联网 发布:linux 怎么引导win 7 编辑:程序博客网 时间:2024/05/24 02:18
题目
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: 3Output: 3Explanation: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
阅读全文
1 0
- leetcode 650. 2 Keys Keyboard
- LeetCode -- 650. 2 Keys Keyboard
- Leetcode 650. 2 Keys Keyboard
- [LeetCode] 650. 2 Keys Keyboard
- leetcode 650. 2 Keys Keyboard
- [LeetCode] 650. 2 Keys Keyboard
- Leetcode: 650. 2 Keys Keyboard
- [LeetCode] 650. 2 Keys Keyboard
- LeetCode-2 Keys Keyboard
- LeetCode:2 Keys Keyboard
- leetcode 650. 2 Keys Keyboard(dp)
- LeetCode 650. 2 Keys Keyboard--动态规划
- [LeetCode] 650. 2 Keys Keyboard ## 题目描述
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- unbuntu16.04安装ROS kinetic 软件安装源问题 或者apt-get无法更新
- 前端小知识积累
- java集合(二)——集合 Set
- 计算机图形学知识点
- ios-异步发送网络请求
- Leetcode 650. 2 Keys Keyboard
- 变态跳台阶(剑指Offer)
- 应用最广泛的工厂模式
- java集合(三)——集合 List
- poj 2528 Mayor's posters 线段树成段更新+离散化
- 序列化和反序列化的简单理解
- ioFile
- 如何安装jQuery?
- 生产者/消费者