Skip to content

Commit 19de7fe

Browse files
committed
src/bin/perfect-squares.rs
1 parent 091cd17 commit 19de7fe

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/bin/perfect-squares.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
fn main() {
2+
println!("{}", Solution::num_squares(12));
3+
println!("{}", Solution::num_squares(13));
4+
}
5+
6+
struct Solution;
7+
8+
impl Solution {
9+
pub fn num_squares(n: i32) -> i32 {
10+
let mut h = std::collections::HashMap::new();
11+
Self::f(n, &mut h)
12+
}
13+
14+
fn f(n: i32, h: &mut std::collections::HashMap<i32, i32>) -> i32 {
15+
if n == 0 {
16+
return 0;
17+
}
18+
19+
if let Some(&x) = h.get(&n) {
20+
return x;
21+
}
22+
23+
let mut s = 0;
24+
25+
let mut m = 1;
26+
while m * m <= n {
27+
let s1 = 1 + Self::f(n - m * m, h);
28+
if s == 0 {
29+
s = s1;
30+
} else {
31+
s = s.min(s1)
32+
}
33+
m += 1;
34+
}
35+
36+
h.insert(n, s);
37+
38+
s
39+
}
40+
}

0 commit comments

Comments
 (0)