[LeetCode] 650. 2 Keys Keyboard

Problem:

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'.

题意分析:题目要求我们求得获得 n 个字符'A'(不能少也不能多)的最小操作步数,操作只有两种选择:

当前字符全部复制(Copy All)和粘(Paste)


解题思路:

为了找出规律,一般可以手动推算前面几项的结果:

n = 1时,结果显然为0,不用复制也不需要粘贴;

n = 2时,复制一遍,粘贴一遍,记为 cp,f(2) = 2;

n = 3时,复制一遍,粘贴两遍,记为 cpp,f(3) = 3;

n = 4时,复制一遍,粘贴三遍,记为cppp;另外一种选择为cpcp,f(4) = 4;

n = 5时,cpppp, f(5) = 5;

n = 6时,cpcpp,f(6) = f(2) + 3(6 / 2) = f(3) + 2(6 / 3)= 5;

n = 7时,cpppppp,f(7) = 7;

n = 8时,cpcppp或cpcpcp,f(8) = f(2) + 4(8 / 2) = f(4) + 2(8 / 4) = 6;

n = 9时,cppcpp,f(9) = f(3) + 3(9 / 3)= 6;

n = 10时,cppppcp或cpcpppp,f(10) = f(2) + 5(10 / 2)= f(5) + 2(10 / 5)= 7;

...

总结规律: f(n) = f(i) + n / i ,其中i为能整除n的整数,若n为素数,很容易理解,结果为其本身。


Solution:

class Solution {
public:
    int minSteps(int n) {
        if (n == 1) return 0;
        vector<int> steps(n+1, 0);
        for (int i = 2; i <= n; i++)
            steps[i] = i;
        for (int i = 2; i <= n; i++) {
            for (int j = i / 2; j > 1; j--) {
                if (i % j == 0) {
                    steps[i] = steps[j] + i / j;
                    break;
                }
            }
        }
        return steps[n];
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值