LeetCode //C - 279. Perfect Squares

279. Perfect Squares

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

Constraints:
  • 1 < = n < = 1 0 4 1 <= n <= 10^4 1<=n<=104

From: LeetCode

Link: 279. Perfect Squares


Solution:

Ideas:
  1. Initialize an array dp with size n+1 and fill it with INT_MAX to represent infinity, since we are looking for the minimum value. This array will store the least number of perfect squares that sum to every number up to n.
  2. Set dp[0] = 0 because there are 0 perfect squares that sum to 0.
  3. Use nested loops to populate the dp array. The outer loop iterates through each number from 1 to n, and the inner loop iterates through each square number jj that could be used to form i. It updates dp[i] to the minimum between its current value and dp[i - jj] + 1.
  4. After filling the dp array, dp[n] contains the least number of perfect squares that sum to n.
Code:
c 复制代码
int numSquares(int n) {
    int dp[n+1];
    for(int i = 0; i <= n; i++) {
        dp[i] = INT_MAX;
    }
    dp[0] = 0;
    
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j*j <= i; j++) {
            if(dp[i - j*j] != INT_MAX) {
                dp[i] = dp[i] < dp[i - j*j] + 1 ? dp[i] : dp[i - j*j] + 1;
            }
        }
    }
    
    return dp[n];
}
相关推荐
Onlooker129几秒前
LC-单词搜索、分割回文串、N皇后、搜索插入位置、搜索二维矩阵
算法·leetcode
宋康1 分钟前
C/C++ 指针避坑20条
c语言·开发语言·c++
查理零世40 分钟前
【蓝桥杯集训·每日一题2025】 AcWing 6134. 哞叫时间II python
python·算法·蓝桥杯
仟濹41 分钟前
【二分搜索 C/C++】洛谷 P1873 EKO / 砍树
c语言·c++·算法
紫雾凌寒1 小时前
解锁机器学习核心算法|神经网络:AI 领域的 “超级引擎”
人工智能·python·神经网络·算法·机器学习·卷积神经网络
YH_DevJourney1 小时前
Linux-C/C++《C/8、系统信息与系统资源》
linux·c语言·c++
京东零售技术1 小时前
AI Agent实战:打造京东广告主的超级助手 | 京东零售技术实践
算法
Igallta_8136222 小时前
【小游戏】C++控制台版本俄罗斯轮盘赌
c语言·开发语言·c++·windows·游戏·游戏程序
且听风吟ayan2 小时前
leetcode day19 844+977
leetcode·c#
MiyamiKK572 小时前
leetcode_位运算 190.颠倒二进制位
python·算法·leetcode