JavaScript O(n5^⌊n/2⌋) solution using recursion


  • 0
    var findStrobogrammatic = function(n) {
        const nums = ['0', '1', '8', '6', '9'];
        const sides = new Set();
        const res = [];
        buildSides(sides, nums, (n - n % 2) / 2);
        const centers = n % 2 ? ['0', '1', '8'] : [''];
        for (let center of centers) {
            for (let side of sides) {
                res.push(side + center + reverse(side));
            }
        }
        return res;
    };
    
    function buildSides(sides, nums, len, tuple = [], n = 0) {
        if (n === len) {
            sides.add(tuple.map(p => nums[p]).join(''));
            return;
        }
        for (let i = n; i < len; i++) {
            for (let j = +!i; j < nums.length; j++) {
                tuple[i] = j;
                buildSides(sides, nums, len, tuple, i + 1);
            }
        }
    }
    
    function reverse(side) {
        let res = '';
        for (let c of side) {
            res = (c === '6' ? '9' : c === '9' ? '6' : c) + res;
        }
        return res;
    }
    

Log in to reply
 

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