My Java Recursive Solution


  • -1
    A
    public class Solution {
        public List<String> findStrobogrammatic(int n) {
            List<String> rst = helper(n);
            if (n != 1) {
                rst = reduce(rst);
            }
            return rst;
        }
        public List<String> reduce(List<String> list) {
            List<String> rst = new ArrayList<String>();
            for (String s : list) {
                if (s.charAt(0) != '0') {
                    rst.add(s);
                }
            }
            return rst;
        }
        public List<String> helper(int n) {
            List<String> rst = new ArrayList<String>();
            if (n == 0) {
                rst.add("");
                return rst;
            }
            if (n == 1) {
                rst.add("0");
                rst.add("1");
                rst.add("8");
                return rst;
            }
            for (String s : helper(n - 2)) {
                rst.add('1' + s + '1');
                rst.add('6' + s + '9');
                rst.add('8' + s + '8');
                rst.add('9' + s + '6');
                rst.add('0' + s + '0');
            }
            return rst;
        }
    }

Log in to reply
 

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