Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.8 kB
1
Indexable
Never
class Solution {
    
    bool notUsed(int i, int bitMask){
        return (((1 << i) & bitMask) == 0) ? true : false;
    }
    
    int updateMask(int bitMask, int i){
        if(i == 0 && bitMask == 0){
            return bitMask;
        } else {
            int newMask = ((1 << i) | bitMask);
            return newMask;
        }
    }
    
    bool findInMap(int index, bool last, int bitMask, unordered_map<int, unordered_map<bool, unordered_map<int, int>>> &mp){
        if(
                mp.find(index) != mp.end() &&
                mp[index].find(last) != mp[index].end() &&
                mp[index][last].find(bitMask) != mp[index][last].end()
        ) return true;
        return false;
    }
    
    
    int dp(int index, bool last, int bitMask, string &n, unordered_map<int, unordered_map<bool, unordered_map<int, int>>> &mp){
        
        if(index == n.size()){
            return mp[index][last][bitMask] =  (bitMask > 1) ? 1 : 0;
        }
        else if(findInMap(index, last, bitMask, mp))return mp[index][last][bitMask];
        else{
            int from = 0;
            int till = (last ? n[index]-'0': 9);
            int countRes = 0;
            for(int i = from; i <= till; i++ ){
                if(notUsed(i, bitMask)){
                    int newBitMask = updateMask(bitMask, i);
                    countRes = countRes + dp(index+1, (last && (i == till)), newBitMask, n, mp);
                }
            }
            return mp[index][last][bitMask] = countRes;
        }
    }    
    
    
public:
    int numDupDigitsAtMostN(int n) {
        string strN = to_string(n);
        unordered_map<int, unordered_map<bool, unordered_map<int, int>>> mp;
        return n- dp(0, true, 0, strN, mp);        
    }
};