LeetCode 247. Strobogrammatic Number II

21 篇文章 0 订阅
20 篇文章 0 订阅

原题网址:https://leetcode.com/problems/strobogrammatic-number-ii/

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.

For example,
Given n = 2, return ["11","69","88","96"].

Hint:

  1. Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
思路:深度优先搜索,n为奇数和偶数的情况单独处理。

public class Solution {
    private char[] self = {'0', '1', '8'};
    private char[] pair = {'0', '1', '6', '8', '9'};
    private char[] strobo = {'0', '1', ' ', ' ', ' ', ' ', '9', ' ', '8', '6'};
    private void find(char[] buf, boolean zero, int step, List<String> results) {
        if ((step<<1) == buf.length) {
            for(int i=step, j=step-1; i<buf.length; i++, j--) buf[i] = strobo[buf[j]-'0'];
            results.add(new String(buf));
            return;
        } else if ((step<<1) == buf.length-1) {
            for(int i=step+1, j=step-1; i<buf.length; i++, j--) buf[i] = strobo[buf[j]-'0'];
            for(int i=0; i<self.length; i++) {
                buf[step] = self[i];
                results.add(new String(buf));
            }
            return;
        }
        for(int i=0; i<pair.length; i++) {
            if (buf.length>1 && zero && pair[i]=='0') continue;
            buf[step] = pair[i];
            find(buf, false, step+1, results);
        }
    }
    public List<String> findStrobogrammatic(int n) {
        List<String> results = new ArrayList<>();
        find(new char[n], true, 0, results);
        return results;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值