[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'}};};