0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #753: Cracking the Safe

Posted at
import Foundation

class Solution {
    func crackSafe(_ n: Int, _ k: Int) -> String {
        var totalSize = Int(pow(Double(k),Double(n)))
        var str = ""
        for _ in 0..<n {
            str += "0"
        }
        var visited: Set<String> = [str]
        if dfs(&str, totalSize, n, k, &visited) {
            return str
        }
        return ""
    }
    
    private func dfs(_ str: inout String, _ totalSize: Int, _ n: Int, _ k: Int, _ visited: inout Set<String>) -> Bool {
        if visited.count == totalSize {
            return true
        }
        for i in stride(from: 0, to: k, by: 1) {
            var tmp = String(str.suffix(n-1)) + String(i)
            if !visited.contains(tmp) {
                str += String(i)
                visited.insert(tmp)
                if dfs(&str, totalSize, n, k, &visited) {
                    return true
                }
                str = String(str.dropLast())
                visited.remove(tmp)
            }
        }
        return false
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?