Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commitd33484c

Browse files
authored
Create 279. Perfect Squares.md
1 parent15446b2 commitd33484c

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+
classSolution {
25+
26+
var cache= [Int:Int]()
27+
var perfectSquare= [Int]()
28+
29+
funcfindSum(count:Int,num:Int)->Bool {
30+
switch count {
31+
case0:
32+
returnfalse
33+
case1:
34+
guardlet c= cache[num]else {
35+
returnfalse
36+
}
37+
return c==1
38+
default:
39+
if cache[num]!=nil {
40+
returntrue
41+
}
42+
for snin perfectSquare {
43+
iffindSum(count: count-1,num: num- sn) {
44+
cache[num]= count
45+
returntrue
46+
}
47+
}
48+
returnfalse
49+
}
50+
}
51+
52+
funcisPerfectSquare(n:Int)->Bool {
53+
let sqN=Int(sqrt(Double(n)))
54+
return sqN* sqN== n
55+
}
56+
57+
funcnumSquares(_n:Int)->Int {
58+
guard n>0else {
59+
return0
60+
}
61+
for iin1...n {
62+
ifisPerfectSquare(n: i) {
63+
perfectSquare.append(i)
64+
cache[i]=1
65+
}
66+
}
67+
for iin1...n {
68+
iffindSum(count: i,num: n) {
69+
return i
70+
}
71+
}
72+
return n
73+
}
74+
}
75+
```

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp