[LeetCode] 247. Strobogrammatic Number II

Problem

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Find all strobogrammatic numbers that are of length = n.

Example:

Input: n = 2
Output: ["11","69","88","96"]

Solution

class Solution {
    public List<String> findStrobogrammatic(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) return res;
        if (n == 1) return Arrays.asList("0", "1", "8");
        Map<Character, Character> map = new HashMap<Character, Character>();
        map.put('0', '0');
        map.put('1', '1');
        map.put('6', '9');
        map.put('8', '8');
        map.put('9', '6');
        dfs(map, new char[n], 0, n, res);
        return res;
    }
    private void dfs(Map<Character, Character> map, char[] buffer, int index, int n, List<String> res) {
        // when index just passed the mid point, (n+1)/2 works for both odd and even
        if (index == (n+1)/2) {
            res.add(String.valueOf(buffer));
            return;
        }
        for (char ch: map.keySet()) {
            if (index == 0 && n > 1 && ch == '0') continue;
            if (index == n/2 && (ch == '6' || ch == '9')) continue;
            buffer[index] = ch;
            buffer[n-1-index] = map.get(ch);
            dfs(map, buffer, index+1, n, res);
        }
    }
}
阅读 787

推荐阅读
Road to Glory
用户专栏

對酒當歌,人生幾何?譬如朝露,去日苦多。

22 人关注
639 篇文章
专栏主页
目录