[LeetCode] 650. 2 Keys Keyboard ## 题目描述

来源:互联网 发布:武义网络电视 编辑:程序博客网 时间:2024/05/24 01:37

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

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

分析

当一个操作对更多的字母进行操作时,总的操作数更少,同时也要用更少的操作数获得更多的字母。对n进行因数分解,因数的总和为结果。

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