Leetcode 754. Cracking the Safe

There is a box protected by a password. The password is n digits, where each letter can be one of the first k digits 0, 1, ..., k-1.

You can keep inputting the password, the password will automatically be matched against the last n digits entered.

For example, assuming the password is "345", I can open it when I type "012345", but I enter a total of 6 digits.

Please return any string of minimum length that is guaranteed to open the box after the entire string is inputted.

Example 1:

Input: n = 1, k = 2
Output: "01"
Note: "10" will be accepted too.

 

Example 2:

Input: n = 2, k = 2
Output: "00110"
Note: "01100", "10011", "11001" will be accepted too.

 

Note:

  1. n will be in the range [1, 4].
  2. k will be in the range [1, 10].
  3. k^n will be at most 4096.
 1 public class Solution {
 2     public string CrackSafe(int n, int k) {
 3         var sb = new StringBuilder();
 4         
 5         for (int i = 0; i < n; i++)
 6         {
 7             sb.Append('0');
 8         }
 9         
10         var visited = new HashSet<string>();
11         visited.Add(sb.ToString());
12         
13         DFS(n, k, visited, (int)Math.Pow(k, n), sb);
14         
15         return sb.ToString();
16     }
17     
18     private bool DFS(int n, int k, HashSet<string> visited, int total, StringBuilder sb)
19     {
20         if (visited.Count >= total)
21         {
22             return true;
23         }
24         
25         var prev = sb.ToString(sb.Length - n + 1, n - 1);
26         
27         for (int i = 0; i < k; i++)
28         {
29             var cur = prev + i.ToString();
30             if (!visited.Contains(cur))
31             {
32                 visited.Add(cur);
33                 
34                 sb.Append(i);
35                 
36                 if (DFS(n, k, visited, total, sb))
37                 {
38                     return true;
39                 }
40                 else
41                 {
42                     visited.Remove(cur);
43                     sb.Remove(sb.Length - 1, 1);
44                 }
45             }
46         }
47         
48         return false;
49     }
50 }

 

posted @ 2017-12-29 07:58  逸朵  阅读(498)  评论(0)    收藏  举报