ํ์ด
numbers์ ๊ฐ์ ์ ์ฅํ ๋ณ์๋ฅผ ๋ง๋ค์ด์ค๋๋ค. -> var numbersCopy = [Int]()
target ๊ฐ์ ์ ์ฅํ ๋ณ์๋ฅผ ๋ง๋ค์ด์ค๋๋ค. -> var targetCopy = 0
๋ฐฉ๋ฒ์ ์๋ฅผ ์ ์ฅํ ๋ณ์๋ฅผ ๋ง๋ค์ด์ค๋๋ค. -> var count = 0
numbers์ ์ซ์๋ค์ ์ฐจ๋ก๋ก ๋ํ๊ฑฐ๋ ๋บ์ ๋ ๋๊ฐ์ง ๋ชจ๋๋ฅผ ์คํ์ํค๋๋ก ํ์ฌ ๊น์ด๊ฐ(depth) numbers์ ๊ฐฏ์์ ๋๋ฌํ๋ฉด ๋ฐํํ๋๋ก ํ๋ ์ฌ๊ทํจ์๋ฅผ ๋ง๋ค์ด์ค๋๋ค.(dfs) func dfs(_ depth: Int, _ sum: Int) { if depth == numbersCopy.count { ... } return }
numbers์ ๊ฐฏ์์ ๋๋ฌํ์ ๋ ํฉ์ด target์ ๊ฐ๊ณผ ๊ฐ๋ค๋ฉด ๋ฐฉ๋ฒ์ ์๋ฅผ ์ฆ๊ฐ์์ผ์ฃผ๋๋กํด์ค๋๋ค. => if sum == targetCopy { count += 1 }
ํฉ์ ๋ค์ ์ซ์๋ฅผ ๋ํด์ค dfs์ ํฉ์ ๋ค์ ์ซ์๋ฅผ ๋บ dfs๋ฅผ ๊ฐ๊ฐ ์ฌ๊ทํ๋๋ก ํด์ค๋๋ค.
=> dfs(depth + 1, sum + numbersCopy[depth])
dfs(depth + 1, sum - numbersCopy[depth])
์ด๊ธฐ๊ฐ์ผ๋ก dfs์ (0,0)์ ๋ฃ์ด์ฃผ๊ณ numbers๊ฐ [1,1,1,1,1]์ด๊ณ taget์ด 3์ธ ํจ์๋ฅผ ์คํ์ํค๋ฉด
func solution(_ numbers:[Int], _ target:Int) -> Int {
numbersCopy = numbers
targetCopy = target
dfs(0, 0)
return count
}
depth = 1
1
-1
depth = 2
2 0
0 -2
depth = 3
3 1 1 -1
1 -1 -1 -3
depth = 4
4 2 2 0 2 0 0 -2
2 0 0 -2 0 -2 -2 -4
depth = 5
5 3 3 1 3 1 1 -1 3 1 1 -1 1 -1 -1 -3
3 1 1 -1 1 -1 -1 -3 1 -1 -1 -3 -1 -3 -3 -5
3์ธ ์ซ์๊ฐ ์ด 5๊ฐ ์ด๋ฏ๋ก ์ ๋ต์ 5๊ฐ ๋ฉ๋๋ค.
์ด๋ฒ ๋ฌธ์ ๋ ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํ๋ DFS(Depth - First - Search) ๊น์ด์ฐ์ ํ์์ผ๋ก ํ์์ด์ผ ํ๋ ๋ฌธ์ ์๋๋ฐ
DFS๋ฅผ ๋ชจ๋ฅด๊ณ ์์ด์ ์ ๋ง ๋ณต์กํ๊ฒ ์๊ฐํ๋ค๊ฐ ๊ฒฐ๊ตญ ๊ตฌ๊ธ๋งํด์ DFS๋ฌธ์ ์ธ๊ฒ์ ์๊ณ ํ๊ฒ ๋์๋ค.
์ ์ฒด ์ฝ๋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
var numbersCopy = [Int]()
var targetCopy = 0
var count = 0
func dfs(_ depth: Int, _ sum: Int) {
if depth == numbersCopy.count {
if sum == targetCopy {
count += 1
}
return
}
dfs(depth + 1, sum + numbersCopy[depth])
dfs(depth + 1, sum - numbersCopy[depth])
}
func solution(_ numbers:[Int], _ target:Int) -> Int {
numbersCopy = numbers
targetCopy = target
dfs(0, 0)
return count
}
|
'๐ Problem Solution > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
2019 ์นด์นด์ค ๊ฐ๋ฐ์ ๊ฒจ์ธ ์ธํด์ฝ ํํ Swift (0) | 2020.09.07 |
---|---|
2020 ์นด์นด์ค ์ธํด์ฝ ์์ ์ต๋ํ Swift (0) | 2020.09.03 |
ํ๋ก๊ทธ๋๋จธ์ค ์ต์๊ฐ ๋ง๋ค๊ธฐ Swift (0) | 2020.08.28 |
ํ๋ก๊ทธ๋๋จธ์ค ์ต๋๊ฐ๊ณผ ์ต์๊ฐ (0) | 2020.08.28 |
ํ๋ก๊ทธ๋๋จธ์ค ๋ ๋ฐ๋จน๊ธฐ Swift (0) | 2020.08.27 |
๋๊ธ