753. Cracking the Safe
There is a box protected by a password. The password is
ndigits, where each letter can be one of the firstkdigits0, 1, ..., k-1.You can keep inputting the password, the password will automatically be matched against the last
ndigits 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:
nwill be in the range[1, 4].kwill be in the range[1, 10].k^nwill be at most4096.
Approach #1: DFS. [Java]
class Solution {
public String crackSafe(int n, int k) {
String strPwd = String.join("", Collections.nCopies(n, "0"));
StringBuilder sbPwd = new StringBuilder(strPwd);
int total = (int)Math.pow(k, n);
Set<String> seen = new HashSet<>();
seen.add(strPwd);
crackSafeAfter(sbPwd, total, seen, n, k);
return sbPwd.toString();
}
private boolean crackSafeAfter(StringBuilder pwd, int total, Set<String> seen, int n, int k) {
if (seen.size() == total) return true;
String lastDigits = pwd.substring(pwd.length()-n+1);
for (char ch = '0'; ch < '0' + k; ch++) {
String newComb = lastDigits + ch;
if (!seen.contains(newComb)) {
seen.add(newComb);
pwd.append(ch);
if (crackSafeAfter(pwd, total, seen, n, k)) return true;
seen.remove(newComb);
pwd.deleteCharAt(pwd.length() - 1);
}
}
return false;
}
}
Analysis:
In order to guarantee to open the box at last, the input password ought to contain all length-n combinations on digits [0...k-1] - there should be k^n combinations in total.
To make the input password as short as possible, we'd better make each possible length-n combination on digits [0...k-1] occurs exactly once as a substring of the password. The existence of such a password is proved by DeBruijin sequence:
A De Bruijn sequence of order n on a size-k alphabet A is a cyclic sequence in which every possible length-n string on A occurs exactly once as a substring. It has length k^n, which is also the number of distinct substrings of length n on a size-k alphabet; De Bruijn sequences are therefore optimally short.
We reuse last n-1 digits of the input-so-far password as below:
e.g. n = 2, k = 2
all 2-length combinations on [0, 1]:
00 ('00'110)
01 (0'01'10)
11 (00'11'0)
10 (001'10')
The password is 00110
We can utilize DFS to find the password:
goal: to find the shortest input password such that each possible n-length combination of digits [0..k-1] occurs exactly once as a substring.
node: current input password
edge: if the last n - 1 digits of node1 can be transformed to node2 by appending a digit from 0..k-1, there will be an edge between node1 and node2
start node: n repeated 0's
end node: all n-length combinations among digits 0..k-1 are visitedvisitedComb: all combinations that have been visited
Reference:
https://leetcode.com/problems/cracking-the-safe/discuss/153039/DFS-with-Explanations
753. Cracking the Safe的更多相关文章
- [LeetCode] 753. Cracking the Safe 破解密码
There is a box protected by a password. The password is n digits, where each letter can be one of th ...
- 【LeetCode】753. Cracking the Safe 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/cracking ...
- 暴力枚举 + 24点 --- hnu : Cracking the Safe
Cracking the Safe Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:65536KB Total submit u ...
- [LeetCode] Cracking the Safe 破解密码
There is a box protected by a password. The password is n digits, where each letter can be one of th ...
- HNU 12886 Cracking the Safe(暴力枚举)
题目链接:http://acm.hnu.cn/online/?action=problem&type=show&id=12886&courseid=274 解题报告:输入4个数 ...
- [Swift]LeetCode753. 破解保险箱 | Cracking the Safe
There is a box protected by a password. The password is n digits, where each letter can be one of th ...
- HNU 12886 Cracking the Safe 二十四点的判断
经典的一个题,今天竟然写跪了…… 题意: 给你4个数字,让你判断是否能通过四则运算和括号,凑成24点. 思路: 暴力枚举运算顺序和运算符. 代码: #include <iostream> ...
- LeetCode All in One题解汇总(持续更新中...)
突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...
- 算法与数据结构基础 - 深度优先搜索(DFS)
DFS基础 深度优先搜索(Depth First Search)是一种搜索思路,相比广度优先搜索(BFS),DFS对每一个分枝路径深入到不能再深入为止,其应用于树/图的遍历.嵌套关系处理.回溯等,可以 ...
随机推荐
- Win10下ctrl与alt键互换
我之前尝试过用第三方软件修改,但是总是不成功,后来发现直接去修改注册表也不麻烦,记录一下步骤. win + r 输入 regedit 进到这个路径 点击Keyboard Layout 右键,新建一个 ...
- 基于CefSharp开发浏览器(八)浏览器收藏夹栏
一.前言 上一篇文章 基于CefSharp开发(七)浏览器收藏夹菜单 简单实现了部分收藏夹功能 如(添加文件夹.添加收藏.删除.右键菜单部分功能) 后续代码中对MTreeViewItem进行了扩展,增 ...
- node.js详解1
1.运行node脚本 新建app.js 写入代码console.log('hello') cmd终端执行 node app.js 2.node读取环境变量 浏览器地址:ht ...
- Java基础学习--集合
集合 List集合的特点 1.有序的数据集合,存储元素和取出元素的顺序是一致的(存储123,取出123) 2.有索引,包含了一些带索引的方法 3.允许存储重复的元素 List接口中带索引的方法 add ...
- Selenium 4.0beta: Grid 工作原理
Selenium 4.0 beta版已经发布,那么距离正式版已经不远了,在Selenium 4.0中变化比较大的就是Grid了,本文翻译了官方文档,重点介绍Grid 4的工作原理 Selenium G ...
- C#连接Excel读取与写入数据库SQL ( 上 )
第一次写C#与sql的东西,主要任务是从Excel读取数据,再存到SQL server中. 先上读取Excel文件的code如下. public bool GetFiles(string equipN ...
- 2.1 Python3基础-内置函数(print&input)
>>返回主目录 源代码 # 内置函数:输入/输出 name = 'Portos' age = 18 sex = 'man' score = 99.5 print('Hello World! ...
- git的回滚与撤销【reset and revert】
git的工作流程-- 3个区域 工作区:我们可以看到的文件内容 在操作 git add 之前的!! 缓存区:是不可见的 已经git add操作,还没git commit -m "" ...
- 海岸线、科赫曲线、turtle、递归
本章绘图要点: turtle模块:python标准库自带的一个模块,可用来绘制二维图形.该模块封装了底层的数据处理逻辑,向外提供了更符合手工绘图习惯的接口函数,适用于绘制对质量.精度要求不高的图形. ...
- APK瘦身属性——android:extractNativeLibs
先描述一下结论: android:extractNativeLibs = true时,gradle打包时会对工程中的so库进行压缩,最终生成apk包的体积会减小. 但用户在手机端进行apk安装时,系统 ...