[leetcode] 247. Strobogrammatic Number II 解题报告

本文介绍了一种使用递归深度优先搜索(DFS)的方法来找出所有长度为n的旋转对称数。通过逐层构建字符串并考虑特殊字符的对称性,确保了生成的所有数在旋转180度后仍保持不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: 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.

思路: 可以像是一层层的给字符串从里向外穿衣服一样DFS生成所有的解.

其中翻转之后和自身相等有0, 1, 8, 在n为奇数的情况下最里面的一个数可以为这三个数的任意一个. 再外边就一次给两端添加一个对称的字符. 如果是最外层的话需要注意不能是为0.

代码如下:

class Solution {
public:
    void DFS(int n, string str)
    {
        if(n==0) return result.push_back(str);
        if(n%2==1) for(auto val: same) DFS(n-1, val);
        if(n%2==1) return;
        for(int i = (n==2)?1:0; i < two.size(); i++)
            DFS(n-2, two[i].first + str + two[i].second);
    }
    
    vector<string> findStrobogrammatic(int n) {
        if(n <= 0) return {};
        DFS(n, "");
        return result;
    }
private:
    vector<string> result;
    vector<string> same{"0", "1", "8"};
    vector<pair<char,char>> two{{'0','0'},{'1','1'},{'6','9'},{'8','8'},{'9','6'}};
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值