|
| 1 | +/** |
| 2 | + * [279] Perfect Squares |
| 3 | + * |
| 4 | + * Given an integer n, return the least number of perfect square numbers that sum to n. |
| 5 | + * 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. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * |
| 9 | + * Input: n = 12 |
| 10 | + * Output: 3 |
| 11 | + * Explanation: 12 = 4 + 4 + 4. |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * |
| 15 | + * Input: n = 13 |
| 16 | + * Output: 2 |
| 17 | + * Explanation: 13 = 4 + 9. |
| 18 | + * |
| 19 | + * |
| 20 | + * Constraints: |
| 21 | + * |
| 22 | + * 1 <= n <= 10^4 |
| 23 | + * |
| 24 | + */ |
| 25 | +pub struct Solution {} |
| 26 | + |
| 27 | + // discuss: https://leetcode.com/problems/perfect-squares discuss/?currentPage=1&orderBy=most_votes&query= |
| 28 | + |
| 29 | +// submission codes start here |
| 30 | +use std::cmp::min; |
| 31 | + |
| 32 | +impl Solution { |
| 33 | + pub fn num_squares(n: i32) -> i32 { |
| 34 | + let mut nums = vec![]; |
| 35 | + for i in 1..n { |
| 36 | + if i * i > n { |
| 37 | + break; |
| 38 | + } else { |
| 39 | + nums.push(i * i); |
| 40 | + } |
| 41 | + } |
| 42 | + // println!("nums is {:?}", nums); |
| 43 | + let l = nums.len(); |
| 44 | + // indeed a package problem |
| 45 | + // dp[i][j] = min(dp[i - 1][j - nums[i]] + 1) for nums[i] <= j |
| 46 | + let mut dp = vec![vec![n; n as usize + 1]; l + 1]; |
| 47 | + for i in 0..=l as usize { |
| 48 | + dp[i][0] = 0; |
| 49 | + } |
| 50 | + |
| 51 | + for i in 1..=l as usize { |
| 52 | + for j in 1..=n as usize { |
| 53 | + if nums[i - 1] <= j as i32 { |
| 54 | + dp[i][j] = min(dp[i][j - nums[i - 1] as usize] + 1, dp[i - 1][j]); |
| 55 | + } else { |
| 56 | + dp[i][j] = dp[i - 1][j]; |
| 57 | + } |
| 58 | + // println!("dp[{}][{}] is {}", i, j, dp[i][j]); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return dp[l as usize][n as usize]; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// submission codes end |
| 67 | + |
| 68 | +#[cfg(test)] |
| 69 | +mod tests { |
| 70 | + use super::*; |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_279() { |
| 74 | + assert_eq!(Solution::num_squares(9), 1); |
| 75 | + assert_eq!(Solution::num_squares(12), 3); |
| 76 | + assert_eq!(Solution::num_squares(13), 2); |
| 77 | + } |
| 78 | +} |
0 commit comments