- [Leetcode 3669. Balanced K-Factor Decomposition](#Leetcode 3669. Balanced K-Factor Decomposition)
- [1. 解题思路](#1. 解题思路)
- [2. 代码实现](#2. 代码实现)
1. 解题思路
这一题思路上同样还是比较直观的,就是分两步:
- 第一步就是找出给定的 n n n的所有质因数;
- 第二步就是探索有的 n n n的质因数的组合,将其合并为 k k k个因数,并使其最为接近。
其中,关于第一步,我们只需要提前计算出所有的质因数,然后遍历一下看看 n n n的所有质因数的分布即可。
然后关于第二步,我们使用一个动态规划即可处理。
2. 代码实现
给出python代码实现如下:
python
def get_primes(n):
primes = []
status = [0 for _ in range(n+1)]
for i in range(2, n+1):
if status[i] == 1:
continue
primes.append(i)
for j in range(i, n+1, i):
status[j] = 1
return primes
PRIMES = get_primes(10**5)
class Solution:
def minDifference(self, n: int, k: int) -> List[int]:
def split(n):
factors = []
for p in PRIMES:
if n < p:
break
while n % p == 0:
factors.append(p)
n = n // p
return factors
factors = split(n)
if len(factors) <= k:
return [1] * (k-len(factors)) + factors
# print(factors)
@lru_cache(None)
def dfs(arr):
if len(arr) == k:
return arr
ans = []
e = arr[0]
for i, num in enumerate(arr):
if i == 0:
continue
nxt = list(arr[1:i] + arr[i+1:])
bisect.insort(nxt, e * num)
candi = dfs(tuple(nxt))
if ans == [] or candi[-1]-candi[0] < ans[-1]-ans[0]:
ans = candi
return ans
return dfs(tuple(factors))
提交代码评测得到:耗时12ms,占用内存18.55MB。