[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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值