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
原创粉丝点击