From b562aea45e0b578d56777dfaf6986f08222e095b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 8 Feb 2024 10:24:08 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB279.=20Perfect=20Squares?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/perfect-squares.rs | 65 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 rs/perfect-squares.rs diff --git a/rs/perfect-squares.rs b/rs/perfect-squares.rs new file mode 100644 index 0000000..0234635 --- /dev/null +++ b/rs/perfect-squares.rs @@ -0,0 +1,65 @@ +use std::cmp; + +// We are guaranteed ‹n ∈ ⟨1 ; 10⁴⟩› +const UPPER_BOUND: i32 = 2000000000; + +// Flag for unknown values +const UNKNOWN: i32 = -1; + +struct Solver { + dp: Vec, +} + +impl Solver { + fn new(n: i32) -> Self { + let mut dp = vec![UNKNOWN; (n as usize) + 1]; + dp[0] = 0; + + Self { dp } + } + + fn solve(&mut self, n: i32) -> i32 { + if n < 0 { + return UPPER_BOUND; + } + + let idx = n as usize; + if self.dp[idx] != UNKNOWN { + return self.dp[idx]; + } + + self.dp[idx] = UPPER_BOUND; + for i in (1..=n).take_while(|i| i * i <= n) { + self.dp[idx] = cmp::min(self.dp[idx], 1 + self.solve(n - i * i)); + } + + self.dp[idx] + } +} + +struct Solution {} +impl Solution { + pub fn num_squares(n: i32) -> i32 { + Solver::new(n).solve(n) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1() { + assert_eq!(Solution::num_squares(12), 3); + } + + #[test] + fn test_2() { + assert_eq!(Solution::num_squares(13), 2); + } + + #[test] + fn test_3() { + assert_eq!(Solution::num_squares(55), 4); + } +}