Skip to content

Commit

Permalink
solve(programmers): LV2_타겟 넘버_kt
Browse files Browse the repository at this point in the history
# id: 문제 id를 숫자로 작성
# categories : 해당 문제의 유형을 ,로 구분하여 작성
# tags : 해당 문제의 태그를 ,로 구분하여 작성
# time : 해당 문제 풀이에 걸린 시간을 분단위 숫자로 작성
# try : 해당 문제에 몇번의 시도를 했는지 숫자로 작성
# help: 해당 문제에 외부의 도움을 받았는지 true/false로 작성
# url : 해당 문제의 url을 작성
id: 43165
categories: [DFS,BFS]
tags: []
time: 20
try: 1
help: false
url: https://school.programmers.co.kr/learn/courses/30/lessons/43165
  • Loading branch information
gogumaC committed Aug 20, 2024
1 parent e8c90c7 commit ae31c83
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/algorithmProblems/programmers/LV2_타겟넘버.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import kotlin.collections.ArrayDeque
class Solution {
fun solutionWithBFS(numbers: IntArray, target: Int): Int {
var answer = 0
val q=ArrayDeque<Pair<Int,Int>>()
q.add(Pair(0,-1))
var count=0
while(q.isNotEmpty()){
val (current,depth)=q.removeFirst()
if(depth==numbers.size-1) continue
val plus=current+numbers[depth+1] to depth+1
val minus=current-numbers[depth+1] to depth+1
if(depth+1==numbers.size-1){
if(plus.first==target) count++
if(minus.first==target) count++
}
q.add(plus)
q.add(minus)
}
return count
}

var count=0
fun solutionWithDFS(numbers: IntArray, target: Int): Int {
var answer = 0
dfs(numbers,0,0,target)
return count
}

fun dfs(numbers:IntArray,depth:Int,total:Int,target:Int){
if(depth==numbers.size){
if(total==target) count++
return
}
dfs(numbers,depth+1,total+numbers[depth],target)
dfs(numbers,depth+1,total-numbers[depth],target)
}
}

0 comments on commit ae31c83

Please sign in to comment.