LeetCode Exercise

Logo

This is my LeetCode exercise.
You can see all question I did here.

View the Project on GitHub YaoyuanHsu/LeetCode_Exercise

279. Perfect Squares

Description

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.

Examples

Example 1:

Example 2:

Constraints:

Code

#define MIN(x, y) x<y ? x : y

int numSquares(int n){
    int *result = malloc((n+1) * sizeof(int));
    int sqrt_bound = 0;
    for(int num = 0 ; num <= n ; num++){
        result[num] = num;
        sqrt_bound = sqrt(num);
        for(int remain_sqrt = 1 ; remain_sqrt <= sqrt_bound ; remain_sqrt++)
            result[num] = MIN(result[num], result[num-remain_sqrt*remain_sqrt] + 1);
    }
    
    return result[n];
}

Complexity

Space Time
$O(N)$ $O(N^{3/2})$

Result