[Leetcode] 247. Strobogrammatic Number II 解题报告
来源:互联网 发布:数据库小项目 编辑:程序博客网 时间:2024/06/05 03:41
题目:
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"]
.
思路:
这道题目既可以用回溯法完成,也可以用深度优先搜索完成。回溯法的解法相对比较普通,所以我们这里给出一种深度优先搜索的解法:
1)如果n是奇数,那么最中间一位只能是0,1或者8,所以我们首先递归地给出n的前一半的可能结果(此时后一半的对应结果也就已经确定了),然后把0,1或者8嵌在最中间就可以了。
2)如果n是偶数,那么只需要递归地给出n的前一半的可能结果(此时后一半的对应结果也就已经确定了),然后把0,1,8,6或者9加在最两边就可以了。
唯一需要小心的是:0不能出现在数字的首位。
代码:
class Solution {public: vector<string> findStrobogrammatic(int n) { // This version can make me better to understand the principle and idea of DFS if(n <= 0) { return {}; } vector<string> result; dfs(n, "", result); return result; }private: void dfs(int n, string str, vector<string> &result) { if(n == 0) { return result.push_back(str); } if(n % 2 != 0) { for(auto val : same) { dfs(n-1, val, result); } } else { for(int i = (n == 2) ? 1 : 0; i < two.size(); ++i) { dfs(n-2, two[i].first + str + two[i].second, result); } } } vector<string> same{"0", "1", "8"}; vector<pair<char,char>> two{{'0','0'},{'1','1'},{'6','9'},{'8','8'},{'9','6'}};};
阅读全文
0 0
- [leetcode] 247. Strobogrammatic Number II 解题报告
- [Leetcode] 247. Strobogrammatic Number II 解题报告
- [leetcode] 246. Strobogrammatic Number 解题报告
- [leetcode] 248. Strobogrammatic Number III 解题报告
- [Leetcode] 246. Strobogrammatic Number 解题报告
- [Leetcode] 248. Strobogrammatic Number III 解题报告
- LeetCode 247. Strobogrammatic Number II
- LeetCode 247. Strobogrammatic Number II
- Leetcode 247. Strobogrammatic Number II (数学,递归)
- 247. Strobogrammatic Number II
- LeetCode 题解(239) : Strobogrammatic Number II
- LeetCode解题报告 --- Single Number II
- LeetCode — Single Number II 解题报告
- LeetCode 137 Single Number II 解题报告
- LeetCode-Ugly Number II-解题报告
- 【LeetCode】Ugly Number II 解题报告
- [leetcode] 264. Ugly Number II 解题报告
- [leetcode] 137. Single Number II 解题报告
- 6.30
- C++入门基础知识
- spring-cloud demo
- 机器学习之numpy和matplotlib学习(十)
- Modbus RTU 主站指令库
- [Leetcode] 247. Strobogrammatic Number II 解题报告
- OGRE win10 Vs2015编译
- 性能优化——内存泄漏(2)工具分析篇
- C++四个默认成员函数+运算符重载
- hdu 3060 Area2(多边形的并模板题)
- <NOIP> 12 . P1980 计数问题
- Python从零开始写爬虫(一)requests库使用
- Java中ArrayList集合中subList方法注意事项
- 从0到1:我是如何在一年内无师自通机器学习的?