【第十周】650. 2 Keys Keyboard

原题

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: 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:
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、需要观察题目所给条件,分析隐藏属性以找到最优算法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值