LeetCode: Generate Parentheses
๋ฐฑํธ๋ํน + ์คํ๊ดํธ๋ฅผ ์กฐํฉํ ๋ฌธ์ ์๋ค. ๋ ๊ฐ์ง ๋ฉ์๋๋ฅผ ๋ง๋ค์ด์ ์ฒ๋ฆฌํ๋ค.
- n๊ฐ์ ๋ชจ๋ ๊ดํธ ์กฐํฉ์ ๋ง๋๋
pick(toPick:)
- ๋ฌธ์์ด ๋ฐฐ์ด์ด ์ฌ๋ฐ๋ฅธ ๊ดํธ ์กฐํฉ์ธ์ง ํ๋ณํ๋
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()
}
}
๋ฐ์ํ
๋๊ธ
์ด ๊ธ ๊ณต์ ํ๊ธฐ
-
๊ตฌ๋
ํ๊ธฐ
๊ตฌ๋ ํ๊ธฐ
-
์นด์นด์คํก
์นด์นด์คํก
-
๋ผ์ธ
๋ผ์ธ
-
ํธ์ํฐ
ํธ์ํฐ
-
Facebook
Facebook
-
์นด์นด์ค์คํ ๋ฆฌ
์นด์นด์ค์คํ ๋ฆฌ
-
๋ฐด๋
๋ฐด๋
-
๋ค์ด๋ฒ ๋ธ๋ก๊ทธ
๋ค์ด๋ฒ ๋ธ๋ก๊ทธ
-
Pocket
Pocket
-
Evernote
Evernote