Perfect Squares (M)
題目
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
題意
將一個整數轉換為x個完全平方數的和,求x的最小值,
思路
直接使用遞回會超時,使用記憶化搜索進行優化,
也可以使用動態規劃:dp[i]表示整數i最少由dp[i]個完全平方數相加得到,dp[i]初始值為1(自己就是完全平方數)或i(由i個1相加得到),遞推公式為:\(dp[i]=Math.min(dp[i], dp[j] + dp[i-j])\),
代碼實作
Java
記憶化搜索
class Solution {
public int numSquares(int n) {
int[] record = new int[n + 1];
Arrays.fill(record, -1);
return dfs(n, record);
}
private int dfs(int n, int[] record) {
if (n <= 1) {
return n;
}
if (record[n] != -1) {
return record[n];
}
int min = n;
for (int i = 1; i * i <= n; i++) {
min = Math.min(min, dfs(n - i * i, record));
}
record[n] = min + 1;
return min + 1;
}
}
動態規劃
class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
int root = (int) Math.sqrt(i);
dp[i] = root * root == i ? 1 : i;
for (int j = 1; j <= i / 2; j++) {
dp[i] = Math.min(dp[i], dp[i - j] + dp[j]);
}
}
return dp[n];
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/41143.html
標籤:其他
上一篇:0021. Merge Two Sorted Lists (E)
下一篇:POJ 1000:兩數之和
