码迷,mamicode.com
首页 > 其他好文 > 详细

753. Cracking the Safe

时间:2018-10-31 12:41:00      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:ica   map   minimum   rac   please   solution   keep   nod   tin   

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.
class Solution:
    def crackSafe(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        seen = set()
        ans = []
        def dfs(node):
            for x in map(str, range(k)):
                nei = node + x
                if nei not in seen:
                    seen.add(nei)
                    dfs(nei[1:])
                    ans.append(x)
        dfs("0" * (n-1))
        return "".join(ans) + "0" * (n-1)

思路是利用欧拉回路的方法,使用dfs走遍所有节点。

753. Cracking the Safe

标签:ica   map   minimum   rac   please   solution   keep   nod   tin   

原文地址:https://www.cnblogs.com/bernieloveslife/p/9830113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!