6ms Java Solution, beats 91% of solutions


  • 0
    public class Solution {
        public List<String> findStrobogrammatic(int n) {
            char[][] pairs = new char[][]{{'0','0'},{'1','1'},{'6','9'},{'8','8'},{'9','6'}};
            List<String> res = new ArrayList<>();
            findStrobogrammaticHelper(pairs, 0, n - 1, new char[n], res);
            return res;
        }
    
        private void findStrobogrammaticHelper(char[][] pairs, int left, int right, char[] tmpRes, List<String> res) {
            if(left > right) {
                res.add(new String(tmpRes));
                return;
            }
    
            for(char[] pair: pairs) {
                if(tmpRes.length > 1 && left == 0 && pair[0] == '0') continue;
                if(left == right && (pair[0] == '6' || pair[0] == '9')) continue;
    
                tmpRes[left] = pair[0];
                tmpRes[right] = pair[1];
                findStrobogrammaticHelper(pairs, left + 1, right - 1, tmpRes, res);
            }
        }
    }
    

Log in to reply
 

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