Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func findDic(_ dics:[[Character]], _ str: String) -> [[Int]]{
- //生成一个 char 对 set of dic index的 dictionary
- var map = [Character: Set<Int>]() // char - list of dic(index)
- for (index, dic) in dics.enumerated(){
- for char in dic{
- map[char, default: Set<Int>()].insert(index)
- }
- }
- //对于每个位置开始dfs (start with 0)
- let arr = Array(str)
- var visited = Set<Int>()
- var curr = [Int]()
- var result = [[Int]]()
- print(map)
- dfs(map, &visited, arr, 0, &curr, &result)
- return result
- }
- func dfs(_ map: [Character: Set<Int>], _ visited: inout Set<Int>, _ arr: [Character], _ start: Int, _ curr : inout [Int], _ result: inout [[Int]]){
- if start == arr.count{
- result.append(curr)
- return
- }
- if let list = map[arr[start]]{
- for index in list{
- if !visited.contains(index) {
- visited.insert(index)
- curr.append(index)
- dfs(map, &visited, arr, start + 1, &curr, &result)
- curr.removeLast()
- visited.remove(index)
- }
- }
- }
- }
- let dice : [Character] = ["A","B","A"]
- let dice2 : [Character] = ["B","B","B"]
- let dice3 : [Character] = ["C","D","A"]
- let dices = [dice, dice2, dice3]
- print(findDic(dices, "ABC"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement