We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 091cd17 commit 19de7feCopy full SHA for 19de7fe
src/bin/perfect-squares.rs
@@ -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