[LintCode] Perfect Squares 完全平方数

简介:

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example
Given n = 12, return 3 because 12 = 4 + 4 + 4
Given n = 13, return 2 because 13 = 4 + 9

LeetCode上的原题,请参见我之前的博客Perfect Squares

解法一:

class Solution {
public:
    /**
     * @param n a positive integer
     * @return an integer
     */
    int numSquares(int n) {
        while (n % 4 == 0) n /= 4;
        if (n % 8 == 7) return 4;
        for (int a = 0; a * a <= n; ++a) {
            int b = sqrt(n - a * a);
            if (a * a + b * b == n) {
                return !!a + !!b;
            }
        }
        return 3;
    }
};

解法二:

class Solution {
public:
    /**
     * @param n a positive integer
     * @return an integer
     */
    int numSquares(int n) {
        while (n % 4 == 0) n /= 4;
        if (n % 8 == 7) return 4;
        vector<int> dp(n + 1, INT_MAX);
        dp[0] = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 1; i + j * j <= n; ++j) {
                dp[i + j * j] = min(dp[i + j * j], dp[i] + 1);
            }
        }
        return dp.back();
    }
};

解法三:

class Solution {
public:
    /**
     * @param n a positive integer
     * @return an integer
     */
    int numSquares(int n) {
        while (n > 0 && n % 4 == 0) n /= 4;
        if (n % 8 == 7) return 4;
        int res = n, i = 2;
        while (i * i <= n) {
            int a = n / (i * i), b = n % (i * i);
            res = min(res, a + numSquares(b));
            ++i;
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:完全平方数[LintCode] Perfect Squares ,如需转载请自行联系原博主。

相关文章
|
4月前
|
Java
HDU-2199-Can you solve this equation?
HDU-2199-Can you solve this equation?
32 0
|
4月前
|
Java
HDU-2199-Can you solve this equation
HDU-2199-Can you solve this equation
27 0
|
11月前
codeforces 289 B. Polo the Penguin and Matrix
题目意思是在n*m的矩阵中,你可以对矩阵中的每个数加或者减d,求最少的操作次数,使得矩阵中所有的元素相同。 虽然在condeforces中被分到了dp一类,但完全可以通过排序,暴力的方法解决。
34 0
LeetCode 279. Perfect Squares
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
64 0
LeetCode 279. Perfect Squares
|
Java 索引 Python
Leetcode 54:Spiral Matrix 螺旋矩阵
54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
825 0