LeetCode: -Dynamic Programming-2 Keys Keyboard[650]-复制粘贴问题

题目:

一个A,通过复制粘贴操作,实现n个A需要的最少步数。
每步可以有以下选择:
1、复制,复制已有的所有A;
2、粘贴,粘贴上次复制的内容。

注意:n的范围在[1, 1000]

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

示例:

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

解法:

1. 动态规划解法

对于每个输入 n ,它可以由从n-1开始到1的这些数中,为 n 能整除的数 j 复制得到,需要额外的步数为 : 1 步复制, n / j -1 步粘贴得到(减 1 是因为复制之前已经有 j 个A了)。
代码如下:

class Solution {
public:
    int minSteps(int n) {
        vector<int> temp(n+1, INT_MAX);

        temp[1] = 0;

        for(int i = 2; i <= n; i++){
            for(int j = i-1; j >= 1; j--){
                if(i%j == 0){
                    temp[i] = min(temp[i], temp[j]+1+i/j-1);
                }
            }
        }

        return temp[n];
    }
};

2. 递归解法

对于每个已有的 A 的数目,它需要 2 步成为两倍数目的 A, 需要 3 步成为三倍的 A

对于每个输入规模为 n 的问题,如果 n % 2 == 0,则 规模为 f(n) 得问题可以变为规模为 f(n / 2) 的问题。即

f(n) = f(n/2) + 2

对于每个输入规模为 n 的问题,如果 n % 3 == 0,则 规模为 f(n) 得问题可以变为规模为 f(n / 3) 的问题。即

f(n) = f(n/3) + 3


因此对于每个输入 n ,可以找出从 2n-1 的中能被 n 整除的 i ,将问题规模缩小。

代码如下:

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

3. 非递归解法
We look for a divisor d so that we can make d copies of (n / d) to get n

The process of making d copies takes d steps (1 step of Copy All and d - 1 steps of Paste)

We keep reducing the problem to a smaller one in a loop.

The best cases occur when n is decreasing fast, and method is almost O(log(n))

For example, when n = 1024 then n will be divided by 2 for only 10 iterations, which is much faster than O(n) DP method.

The worst cases occur when n is some multiple of large prime, e.g. n = 997 but such cases are rare.

代码如下:

public int minSteps(int n) {
        int s = 0;
        for (int d = 2; d <= n; d++) {
            while (n % d == 0) {
                s += d;
                n /= d;
            }
        }
        return s;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值