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.
2 parents 47d88c4 + e9c20f3 commit aaa6f9bCopy full SHA for aaa6f9b
DP/PerfectSquares.swift
@@ -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