https://school.programmers.co.kr/learn/courses/30/lessons/43165
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
DFS 깊이 우선 탐색 알고리즘으로 푼 코드
- 탐색하려는 노드의 자식 노드부터 우선 탐색하는 방식
import Foundation
func solution(_ numbers:[Int], _ target:Int) -> Int {
var count = 0
func dfs(index: Int, sum: Int) {
if index == numbers.count{
if sum == target {
count += 1
}
return
}
dfs(index: index+1, sum: sum + numbers[index])
dfs(index: index+1, sum: sum - numbers[index])
}
dfs(index: 0, sum: 0)
return count
}
※1,2번 실행초과
재귀 함수와 Array, Dictionary를 통한 코드
- 필요없는 반복문으로 실행초과 발생
import Foundation
func solution(_ numbers:[Int], _ target:Int) -> Int {
var result = 0
var allcase: [[Int]:Bool] = [:]
var numArray = [Int]()
func visit(_ indexArray: [Int]){
numArray = numbers
for i in indexArray{
numArray[i] *= -1
}
if numArray.reduce(0,+) == target{
allcase[indexArray] = true
result += 1
}else{
allcase[indexArray] = false
}
for i in 0..<numbers.count{
if !indexArray.contains(i){
let sortedArray = (indexArray + [i]).sorted(by:<)
if allcase[sortedArray] == nil{
visit(sortedArray)
}
}
}
}
for i in 0..<numbers.count{
visit([i])
}
return result
}
'Swift랑 친해지기 > programmers 풀기' 카테고리의 다른 글
[프로그래머스] N개의 최소공배수 (Swift) (0) | 2023.09.05 |
---|---|
[프로그래머스] 최댓값과 최솟값 (Swift) (0) | 2023.07.24 |
[프로그래머스] 피로도 (Swift) (0) | 2023.07.10 |
[프로그래머스] 2018 KAKAO BLIND RECRUITMENT[3차] 압축 (Swift) (0) | 2023.06.26 |
[프로그래머스] 2개 이하로 다른 비트 (Swift) -10,11 실행초과 (0) | 2023.06.18 |