๊ธ€ ์ž‘์„ฑ์ž: ์ด์ง€์›๐ŸŒฉ๏ธ

๋ฐฑํŠธ๋ž™ํ‚น + ์Šคํƒ๊ด„ํ˜ธ๋ฅผ ์กฐํ•ฉํ•œ ๋ฌธ์ œ์˜€๋‹ค. ๋‘ ๊ฐ€์ง€ ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์–ด์„œ ์ฒ˜๋ฆฌํ–ˆ๋‹ค.

  1. n๊ฐœ์˜ ๋ชจ๋“  ๊ด„ํ˜ธ ์กฐํ•ฉ์„ ๋งŒ๋“œ๋Š” pick(toPick:)
  2. ๋ฌธ์ž์—ด ๋ฐฐ์—ด์ด ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ์กฐํ•ฉ์ธ์ง€ ํŒ๋ณ„ํ•˜๋Š” isWell(_:)

์ค‘๋ณต์ด ์žˆ์„๊นŒ๋ด Set์œผ๋กœ ์ €์žฅํ•ด์„œ, ์ •๋ ฌํ•ด์„œ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฑธ๋กœ ํ•ด๊ฒฐ.

 

๋ฌธ์ œ

https://leetcode.com/problems/generate-parentheses

 

๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

Swift

class Solution {
    func generateParenthesis(_ n: Int) -> [String] {
        let bracket = ["(", ")"]
        var result = [[String]]()
        var picked = [String]()
        func pick(toPick: Int) {
            if toPick == 0 {
                result.append(picked)
                return
            }

            for i in 0..<2 {
                picked.append(bracket[i])
                pick(toPick: toPick - 1)
                picked.removeLast()
            }
        }

        func isWell(_ arr: [String]) -> Bool {
            var count = 0
            for char in arr {
                if char == "(" {
                    count += 1
                } else {
                    count -= 1
                    if count < 0 {
                        return false
                    }
                }
            }

            return count == 0 ? true : false
        }

        pick(toPick: n * 2)

        var answer = Set<String>()

        for r in result {
            if isWell(r) {
                answer.insert(r.joined())
            }
        }

        return answer.sorted()
    }
}
๋ฐ˜์‘ํ˜•