leetcode 650. 2 Keys Keyboard(2个键的键盘)

探讨通过CopyAll和Paste操作获取n个'A'字符所需的最少步骤。采用两种方法求解:动态规划与递归。动态规划从1到n逐步构建解决方案;递归则从n逆向寻找最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

一开始只有一个字母A,现在要用copy,paste的操作得到n个A。
每次只能copy全部,或者paste,问至少要做多少次操作能得到n个A。

思路:
(1) DP
dp[i]表示得到 i 个A需要操作多少次
显然i = 0和i = 1时不需要操作, dp[0] = dp[1] = 0
i = 2: copy一次,paste一次,dp[2] = 2
i = 3: copy一次,paste 2次,dp[3] = 3
i = 4: 从AA copy一次,paste一次,即dp[4] = dp[2] + 2 = dp[2] + 4/2
i = 5: 从A copy一次,paste 4次,dp[5] = 5
i = 6: 从AAA copy一次,paste一次,即dp[6] = dp[3] + 2 = dp[3] + 6/3

得到n个A操作的上限就是n次,然后在n和上面dp中选较小的
至于dp中选被除的因子,就只能从大到小遍历了

//26ms
    public int minSteps(int n) {
        int[] dp = new int[n+1];
        
        for(int i = 2; i <= n; i++) {
            dp[i] = i;
            for(int j = i-2; j > 1; j --) {
                if(i % j == 0) {
                    int tmp = i / j;
                    dp[i] = Math.min(dp[i], dp[j] + tmp);
                    break;
                }
            }
        }
        
        return dp[n];
    }

(2)递归
上面的DP做了很多不必要的计算,因为只想知道dp[n],但是dp[2]~dp[n]中用不到的部分也被计算了。
如果只想计算和dp[n]相关的部分,那就需要哪个就计算哪个,不需要的不计算
由dp[n]倒着往前计算,需要的部分递归再计算
这里递归的部分就相当于上面的dp[ j ]

//0ms
    public int minSteps(int n) {
        if(n <= 1) {
            return 0;
        }
        
        if(n <= 3) {
            return n;
        }
        
        int result = n;
        for(int i = n-2; i >= 2; i--) {
            if(n % i == 0) {
                result = Math.min(result, minSteps(i) + n/i);
            }
        }
        
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值