[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 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.

思路

采用贪心策略(虽然我没有证明为什么贪心策略是对的)。对于长度为n的密码,我们首先从n个‘0’开始,然后定义prev为当前结果的后n-1个字符,接着我们尝试在ans后面添加一个字符(从k-1到k),从而形成n个字符构成的字符串,如果这个字符串在原来没有出现,则继续添加。为了快速检测哪些字符串已经存在于结果中了,我们用一个哈希表来记录。

代码

class Solution {
public:
    string crackSafe(int n, int k) {
        string ans = string(n, '0');
        unordered_set visited;
        visited.insert(ans);
        for(int i = 0; i < pow(k, n); ++i) {
            string prev = ans.substr(ans.size() - n + 1, n-1);  // the last n - 1 characters
            for(int j = k - 1; j >= 0; --j) {                   // try to append j
                string now = prev + to_string(j);
                if(!visited.count(now)) {
                    visited.insert(now);
                    ans += to_string(j);
                    break;
                }
            }
        }
        return ans;
    }
};

你可能感兴趣的:(IT公司面试习题)