【第十周】650. 2 Keys Keyboard

来源:互联网 发布:pc 触屏 手势软件 编辑:程序博客网 时间:2024/06/18 10:26

原题

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:1.    Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).2.    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].

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

解题思路

题目大意:
现在有1个”A”, 可以使用两种操作“全选复制”与“粘贴”,求获得n个“A”所需要的最少的操作数;这是一个非常有意思的问题。

第一种解题思路:使用经典动态规划来求最小值:对于一个N,从1到N进行循环,状态转移方程为dp[n] = min(dp[i] * (n/i)),即对所有N的因子(除了N本身之外)进行动态规划求最小值,同时使用数组来保存已经获得的最小值。此算法的复杂度为O(n);

另外一种思路:经过观察与思考我们可以发现,每一次复制尽可能多的“A”,所需要的总操作数最少。所以我们每一次只需要找到N的最大因子(除N之外),便能找到最少的操作数。此算法的复杂度为O(logN)。

代码

思路2代码如下:

class Solution {public:    int minSteps(int n) {        int ret = 99999;        if (n == 1) return 0;        for (int i = n-1; i > 0; i--) {            if (n % i == 0) {                return minSteps(i) + n / i;            }        }    }};

总结

1、动态规划是基础的解题思路;
2、需要观察题目所给条件,分析隐藏属性以找到最优算法。