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 <= 104

Rust Solution

struct Solution;

impl Solution {
    fn num_squares(n: i32) -> i32 {
        let n = n as usize;
        let mut dp = vec![std::usize::MAX; n + 1];
        dp[0] = 0;
        for i in 1..=n {
            let mut j = 1;
            while j * j <= i {
                dp[i] = dp[i].min(dp[i - j * j] + 1);
                j += 1;
            }
        }
        dp[n] as i32
    }
}

#[test]
fn test() {
    let n = 12;
    let res = 3;
    assert_eq!(Solution::num_squares(n), res);
    let n = 13;
    let res = 2;
    assert_eq!(Solution::num_squares(n), res);
}

Having problems with this solution? Click here to submit an issue on github.