LeetCode 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:

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:

  1. The n will be in the range [1, 1000].

概述

    最近在LeetCode上刷dp题玩,遇到这个骗子题,居然标中等难度。 

思路

    题目大意:开始有1个A,每次可以复制当前数量的A任意(设为k)遍,该行动需要k个步骤,问得到n个A的最少步骤数。

    首先观察,在一个可能的方案中,A的数量有下述变化:1 -> a0 -> a0*a1 -> a0*a1*a2 ->...-> n

    该方案操作数为a0+a1+...+ak.

    ai(0<=i<=k)都是n的因子。方案操作数实际上就是n的一个因子和。

    直觉想到,如果n=a*b,其中a,b>1,那么n>=2*max(a,b)>=a+b.

    于是n的因子和中,质因子和最小,求质因子和即可。

    一个最大O(n)的简单数学题,dp预处理O(n^2)更适用大n配多输入场合。

代码

class Solution {
public:
    int minSteps(int n) {
        int r=0;
        for(int i=2;i<=n;){
            if(n%i==0){
                r+=i;
                n/=i;
            }else i++;
        }
        return r;
    }
};

http://www.cnblogs.com/hizcard/  转载请注明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值