File tree Expand file tree Collapse file tree 2 files changed +35
-22
lines changed Expand file tree Collapse file tree 2 files changed +35
-22
lines changed Original file line number Diff line number Diff line change @@ -20,20 +20,43 @@ dp[13] = min(
20
20
21
21
So ` dp[n] = min(dp[n - i*i] + 1) ` where ` n - i*i >= 0 ` and ` i ` starts from 1.
22
22
23
+ ### Top-Down DP
24
+ ``` kotlin
25
+ private val memo = hashMapOf<Int , Int >()
26
+
27
+ fun numSquares (n : Int ): Int {
28
+ if (n == 0 ) return 0
29
+ if (n == 1 ) return 1
30
+ if (memo.containsKey(n)) return memo[n]!!
31
+ var results = Int .MAX_VALUE
32
+ for (i in 1 .. n) {
33
+ val square = i * i
34
+ if (square <= n) {
35
+ results = min(results, numSquares(n - square) + 1 )
36
+ } else {
37
+ break
38
+ }
39
+ }
40
+ memo[n] = results
41
+ return results
42
+ }
43
+ ```
44
+
23
45
``` kotlin
24
46
fun numSquares (n : Int ): Int {
25
- if (n <= 1 ) return n
26
- val dp = IntArray (n + 1 )
47
+ val dp = IntArray (n + 1 ) { _ -> Int .MAX_VALUE }
27
48
dp[0 ] = 0
28
49
dp[1 ] = 1
29
-
30
50
for (i in 2 .. n) {
31
- val sqrt = sqrt(i.toDouble()).toInt()
32
- var min = Int .MAX_VALUE
33
- for (j in 1 .. sqrt) {
34
- min = min(dp[i - j * j] + 1 , min)
51
+ // Loop through every perfect square
52
+ for (j in 1 .. i) {
53
+ val square = j * j
54
+ if (square <= i) {
55
+ dp[i] = min(dp[i], dp[i - square] + 1 )
56
+ } else {
57
+ break
58
+ }
35
59
}
36
- dp[i] = min
37
60
}
38
61
return dp[n]
39
62
}
Original file line number Diff line number Diff line change @@ -29,21 +29,11 @@ private fun countLetters(str: String): IntArray {
29
29
}
30
30
31
31
private fun hashCountLetters (countArray : IntArray ): String {
32
- val hash = StringBuilder ()
33
- for (i in 0 until 26 ) {
34
- // Output: a2d6e1
35
- if (countArray[i] > 0 ) {
36
- hash.append(" ${' a' + i} " )
37
- hash.append(" ${countArray[i].toString()} " )
38
- }
39
-
40
- // My attempt (AC) but worse time and space complexity
41
- // Comma is required, to separate the alphabet.
42
- // Output: 2006100000000...
43
- // val x = 'a' + i
44
- // hash.append("${countArray[i].toString()},")
32
+ val s = StringBuilder ()
33
+ for (i in 0 until count.size) {
34
+ s.append(" ${count[i]} ," )
45
35
}
46
- return hash .toString()
36
+ return s .toString()
47
37
}
48
38
```
49
39
You can’t perform that action at this time.
0 commit comments