[leetcode] 650. 2 Keys Keyboard (Medium)

解法一:

暴力DFS搜索,对每一步进行复制还是粘贴的状态进行遍历。

注意剪枝的地方:

1、当前A数量大于目标数量,停止搜索

2、当前剪贴板数字大于等于A数量时,只搜索下一步为粘贴的状态。

Runtime: 8 ms, faster than 46.69% of C++ online submissions for 2 Keys Keyboard.

class Solution
{
public:
  int targetNum = 0;
  int resNum = INT_MAX;
  int minSteps(int n)
  {
    targetNum = n;
    if (n == 1)
      return 0;
    dfs(1, 1, 1);
    return resNum;
  }
  void dfs(int copy, int curNum, int times)
  {
    if (curNum == targetNum)
    {
      resNum = min(times, resNum);
      return;
    }
    else if (curNum >= targetNum)
      return;
    else if (copy >= curNum)
      dfs(copy, curNum + copy, times + 1);
    else
    {
      dfs(curNum, curNum, times + 1);
      dfs(copy, curNum + copy, times + 1);
    }
  }
};

解法二:

当n >= 2的时候,最优策略就是尽可能地生成n的最大因数(n / d)个A,然后进行 Copy 一次 Paste d - 1次操作,

为使n / d尽可能的大,只能使d尽可能的小,于是d从2开始循环。当找到一个d之后,我们接下来只需要解决生成n /d个A的问题,所以在循环中让n变为n / d即可。时间复杂度降低到了O(logn)。
Runtime: 0 ms, faster than 100.00% of C++ online submissions for 2 Keys Keyboard.

class Solution
{
public:
  int minSteps(int n)
  {
    int res = 0;
    int d = 2;
    while (n > 1)
    {
      while (n % d == 0)
      {
        res += d;
        n /= d;
      }
      d++;
    }
    return res;
  }
};

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值