Last active
June 8, 2020 00:54
-
-
Save almaleh/7d230025aed9da24161be9074c177345 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func printXY(_ n: Int) -> [String] { | |
| var explored = Set<Int>() | |
| var stack = [n] | |
| var output = [String]() | |
| while let last = stack.last { | |
| let next = last - 1 | |
| if last == 1 { | |
| // base case | |
| output = ["X", "Y"] | |
| explored.insert(last) | |
| } else { | |
| if explored.contains(next) { | |
| var newOutput = [String]() | |
| for element in output { | |
| newOutput.append(element + "X") | |
| newOutput.append(element + "Y") | |
| } | |
| output = newOutput | |
| } else { | |
| explored.insert(next) | |
| stack.append(next) | |
| continue | |
| } | |
| } | |
| stack.popLast() | |
| } | |
| return output | |
| } | |
| let res = printXY(4) | |
| res.forEach { print($0) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment