ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด ํ•ฉ์˜ ๊ฐœ์ˆ˜

2022. 10. 20. 11:04ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์—ฐ์† ๋ถ€๋ถ„ ์ˆ˜์—ด ํ•ฉ์˜ ๊ฐœ์ˆ˜

 

 

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://school.programmers.co.kr/learn/courses/30/lessons/131701

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

 ๋‚˜์˜ ํ’€์ด

 

๋‚˜๋จธ์ง€ ์—ฐ์‚ฐ์ž๋ฅผ ํ†ตํ•ด ์ˆœํšŒํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ 2๋ฐฐ๋กœ ๋งŒ๋“  ๋’ค์— ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ ๊ตฌํ–ˆ๋‹ค.

ํ•˜์ง€๋งŒ ์ด ํ’€์ด๋Š” for๋ฌธ์„ ๋‘ ๋ฒˆ ์‚ฌ์šฉํ•˜๋ฉด์„œ reduce๋ฅผ ์‚ฌ์šฉํ•ด์„œ์ธ์ง€ ํŠน์ • ์ผ€์ด์Šค์—์„œ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค.

 

๊ทธ๋ž˜์„œ ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ์ฐธ๊ณ ํ–ˆ๋‹ค.

 

import Foundation

func solution(_ elements:[Int]) -> Int {
    var answer: Set<Int> = []
    var arr = [[Int]](repeating: elements, count: 2)
    var flatArr = arr.flatMap{$0}
    let n = elements.count
    
    for i in 0..<n {
        for j in 0..<n {
            answer.insert(flatArr[j..<j+i+1].reduce(0, +))
        }
    }
    
    return answer.count
}

 

 

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

1๋ ˆ๋ฒจ์— ์ˆซ์ž ํ•˜๋‚˜๋งŒ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๊ฒŒ ์„ค์ •ํ•œ DFS์ด๋‹ค.

now๋Š” ํ˜„์žฌ ํƒ์ƒ‰ํ•˜๊ณ ์žˆ๋Š” ์ˆซ์ž์ด๋ฉฐ ์ด๋Š” 1, 2, 3, 4, 5๊ฐ€ ์žˆ์„๋•Œ 5๋’ค์—๋Š” 1์ด ๋‹ค์‹œ ์™€์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋‚˜๋จธ์ง€ ์—ฐ์‚ฐ์ž๋กœ ๋‘์—ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  count == elements.count๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€์žฅ ๊ธด ์ˆ˜์—ด์˜ ํ•ฉ๊นŒ์ง€ ๋„์ถœํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด 1, 2, 3, 4, 5์˜ ์ˆ˜์—ด์—์„œ 3๋ถ€ํ„ฐ 5์˜ ๊ธธ์ด๋ฅผ ๊ฐ–๋Š” ์ˆ˜์—ด์„ ๊ฐ–๋Š”๋‹ค๊ณ  ํ–ˆ์„๋•Œ 3, 4, 5, 1, 2๊ฐ€ ๋  ๊ฒƒ์ด๊ณ  ์ด๋Š” count๊ฐ€ 5๊ฐ€ ๋ ๋•Œ๊นŒ์ง€ ์ง„ํ–‰ํ•˜๊ธฐ ๋–„๋ฌธ์— ๋„๋‹ฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

ํˆฌํฌ์ธํ„ฐ ์•„๋‹ˆ๋ฉด for๋ฌธ๋งŒ ์ƒ๊ฐํ–ˆ์—ˆ๋Š”๋ฐ ์ˆ˜์—ด์˜ ๊ธธ์ด๋งˆ๋‹ค addํ•œ๋‹ค๋Š” ์ ์—์„œ DFS๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋Š” ์•„์ด๋””์–ด๊ฐ€ ์ข‹์•˜๋‹ค.

 

import Foundation

func solution(_ elements:[Int]) -> Int {
    var answer: Set<Int> = []
    
    func DFS(_ now: Int, _ num: Int, _ count: Int) {
        answer.insert(num)
        if count == elements.count { return }
        
        for i in now..<now+1 {
            DFS((i+1) % elements.count, num+elements[i], count+1)
        }
    }
    
    for i in 0..<elements.count {
        DFS((i+1) % elements.count, elements[i], 1)
    }
    return answer.count
    
}