// 动态规划,按照所有的因数来递归分解 classSolution { public: intminSteps(int n){ vector<int> f(n + 1); for (int i = 2; i <= n; ++i) { f[i] = INT_MAX; for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { f[i] = min(f[i], f[j] + i / j); f[i] = min(f[i], f[i / j] + j); } } } return f[n]; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 还可以分解质因数 classSolution { public: intminSteps(int n){ int ans = 0; for (int i = 2; i * i <= n; ++i) { while (n % i == 0) { n /= i; ans += i; } } if (n > 1) { ans += n; } return ans; } };