Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit d33484c

Browse files
authored
Create 279. Perfect Squares.md
1 parent 15446b2 commit d33484c

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

279. Perfect Squares.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# 100. Perfect Squares
2+
3+
### 2020-07-30
4+
5+
Given a positive integer n, find the least number of perfect square numbers (for example, `1, 4, 9, 16, ...`) which sum to n.
6+
7+
Example 1:
8+
```
9+
Input: n = 12
10+
Output: 3
11+
Explanation: 12 = 4 + 4 + 4.
12+
```
13+
14+
Example 2:
15+
```
16+
Input: n = 13
17+
Output: 2
18+
Explanation: 13 = 4 + 9.
19+
```
20+
21+
# Solution
22+
23+
```swift
24+
class Solution {
25+
26+
var cache = [Int: Int]()
27+
var perfectSquare = [Int]()
28+
29+
func findSum(count: Int, num: Int) -> Bool {
30+
switch count {
31+
case 0:
32+
return false
33+
case 1:
34+
guard let c = cache[num] else {
35+
return false
36+
}
37+
return c == 1
38+
default:
39+
if cache[num] != nil {
40+
return true
41+
}
42+
for sn in perfectSquare {
43+
if findSum(count: count - 1, num: num - sn) {
44+
cache[num] = count
45+
return true
46+
}
47+
}
48+
return false
49+
}
50+
}
51+
52+
func isPerfectSquare(n: Int) -> Bool {
53+
let sqN = Int(sqrt(Double(n)))
54+
return sqN * sqN == n
55+
}
56+
57+
func numSquares(_ n: Int) -> Int {
58+
guard n > 0 else {
59+
return 0
60+
}
61+
for i in 1...n {
62+
if isPerfectSquare(n: i) {
63+
perfectSquare.append(i)
64+
cache[i] = 1
65+
}
66+
}
67+
for i in 1...n {
68+
if findSum(count: i, num: n) {
69+
return i
70+
}
71+
}
72+
return n
73+
}
74+
}
75+
```

0 commit comments

Comments
 (0)