[753. Cracking the Safe] C++_AC


  • 0

    In the second loop: for(int digt = k-1; digt >= 0; --digt)

    You cannot start from 0 to k-1. For example, the first time it will be "00", and the next time start from "0" and the new ending will be "01", and next time the start will be "1", and it will end at "10" rather than "11", then the new ending is "0" again, however, all of the possible cases start as "0" have been checked, so the loop will always be "00" or "01"...and here is the error.

    class Solution {
    public:
    string crackSafe(int n, int k) {
        string s = string(n-1, '0');
        unordered_set<string> st;
        //(k) (k) (k) (k) : k*k*k*k = k^4 => k^n, all cases
        int total = (int)pow(k,n);
        int count = 0;
        while(count != total){
            string base_str = s.substr(std::max<int>(s.size()-n + 1,0));
            for(int digt = k-1; digt >= 0; --digt){
                string temp = base_str + to_string(digt);
                if(st.find(temp) == st.end()){
                    st.insert(temp);
                    s += to_string(digt);
                    count++;
                    break;
                }
            }
        }
        return s;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.