Skip to content

Commit e9c20f3

Browse files
author
Yi Gu
committed
[DP] add Solution to Perfect Squares
1 parent ba4438d commit e9c20f3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

DP/PerfectSquares.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/perfect-squares/
3+
* Primary idea: Dynamic Programming, transition function is
4+
* nums[i] = min(nums[i], nums[i - j * j] + 1)
5+
* Time Complexity: O(n^2), Space Complexity: O(n)
6+
*/
7+
8+
class PerfectSquares {
9+
func numSquares(n: Int) -> Int {
10+
guard n > 0 else {
11+
return 0
12+
}
13+
14+
var leastNums = [Int](count: n + 1, repeatedValue: Int.max)
15+
leastNums[0] = 0
16+
17+
for i in 1 ... n {
18+
for j in 1 ... i {
19+
if j * j > i {
20+
break
21+
}
22+
leastNums[i] = min(leastNums[i], leastNums[i - j * j] + 1)
23+
}
24+
}
25+
26+
return leastNums[n]
27+
}
28+
}

0 commit comments

Comments
 (0)