LeetCode解題報告 279. Perfect Squares [medium]
題目描述
Given a positive integer n, find the least number of perfect square numbers (for example, 1,
4, 9, 16, ...
) which sum to n.
For example, given n = 12
, return 3
because 12
= 4 + 4 + 4
; given n = 13
, return 2
because 13
= 4 + 9
.
解題思路
題目很容易理解,將一個數分解為幾個平方數的和,返回最小需要的平方數的個數。
用動態規劃求解,一個數x如果可以表示成a+b*b,那麼最後所求的結果就是組成a所需要的平方數的個數再加1。
狀態轉移方程為dp[a+b*b]=min(dp[a]+1, dp[a+b*b])。
將一個長度為x的陣列,完全平方數初始化為1,其餘數初始化為無窮大,如果一個數是完全平方數,那麼返回的值就是它本身,也就是1;如果一個數不是完全平方數,那麼返回的值就是dp[a]+1,因為此時dp[a+b*b]是無窮大。
程式碼如下:
class Solution {
public:
int numSquares(int n) {
int dp[n+1];
for (int i=0; i<n+1; i++) {
dp[i]=INT_MAX;
}
for (int i=0; i*i<=n; i++) {
dp[i*i]=1;
}
for (int i=0; i<=n; i++) {
for (int j=0; i+j*j<=n; j++) {
dp[i+j*j]=min(dp[i]+1,dp[i+j*j]);
}
}
return dp[n];
}
};
O(N)*O(sqrt(N))
相關文章
- [LeetCode] 279. Perfect SquaresLeetCode
- Leetcode Perfect SquaresLeetCode
- LeetCode-Perfect SquaresLeetCode
- LeetCode解題報告 120. Triangle [medium]LeetCode
- LeetCode解題報告 241. Different Ways to Add Parentheses [medium]LeetCode
- LeetCode解題報告 452. Minimum Number of Arrows to Burst Balloons [medium]LeetCode
- LeetCode解題報告 108. Convert Sorted Array to Binary Search Tree [medium]LeetCode
- Leetcode 第136場周賽解題報告LeetCode
- LeetCode Weekly Contest 96 解題報告LeetCode
- Leetcode Weekly Contest 95解題報告LeetCode
- [LeetCode] 425. Word SquaresLeetCode
- Leetcode Weekly Contest94 解題報告LeetCode
- [leetcode] 252. Meeting Rooms 解題報告LeetCodeOOM
- [Leetcode]279.完全平方數LeetCode
- LeetCode-Perfect RectangleLeetCode
- LeetCode 解題報告 - 2. Add Two NumbersLeetCode
- [Leetcode] 253. Meeting Rooms II 解題報告LeetCodeOOM
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- CF1603E A Perfect Problem 題解
- Doris建立表報錯Failed to find enough host with storage medium問題解決AI
- 【LeetCode】253. Meeting Rooms II 解題報告(C++)LeetCodeOOMC++
- [熵值] 解題報告熵
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解題報告LeetCode
- Leetcode-Medium 621. Task SchedulerLeetCode
- LeetCode - Medium - 322. Coin ChangeLeetCode
- ARC173 解題報告
- 【LeetCode】416. Partition Equal Subset Sum 解題報告(Python & C++)LeetCodePythonC++
- LeetCode解題報告 102. Binary Tree Level Order Traversal [easy]LeetCode
- 【LeetCode】455. Assign Cookies 分發餅乾(Medium)(JAVA)每日一題LeetCodeCookieJava每日一題
- leetcode 掃描線專題 06-leetcode.391 perfect-rectangle 力扣.391 完美矩形LeetCode力扣
- [LeetCode 刷題] 3. 無重複字元的最長子串 (Medium)LeetCode字元
- LeetCode 207. 課程表(Medium)LeetCode
- LeetCode - Medium - 11. Container With Most WaterLeetCodeAI
- CF720B 解題報告
- P10499 解題報告
- leetcode240——搜尋二維矩陣(medium)LeetCode矩陣
- 【演算法解題報告】求眾數演算法
- P11188 解題報告