Easy java recursion, inside out. 8ms


  • 0
    B

    final private String even = "0186969810";
    final private String odd = "018";

    public List<String> findStrobogrammatic(int n) {
        ArrayList<String> list = new ArrayList<String>();
        loop(list, "", n);
        return list;
    }
    
    private void loop(List<String> list, String str, int n) {
        int len = str.length();
        if (len == n) {
            list.add(str);
            return;
        } else if (len == 0 && n % 2 == 1 ) { //adding middle char
            for (int i = 0; i < odd.length(); i++) {
                char c = odd.charAt(i);
                loop(list, "" + c, n);
            }
        } else {
            for (int j = n - len == 2 ? 1 : 0; j < even.length() / 2; j++) { 
                char left = even.charAt(j);
                char right = even.charAt(even.length() - j - 1);
                loop(list, left + str + right, n);
            }
        }
    }

Log in to reply
 

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