【Lintcode】776. Strobogrammatic Number II

题目地址:

https://www.lintcode.com/problem/strobogrammatic-number-ii/description

如果一个数,对其翻转 180 ° 180\degree 后与自己相等,那么就称此数为Strobogrammatic数。求所有长度为 n n 的Strobogrammatic数。

容易知道,如果 s [ 0 , . . . , l e n 1 ] s[0,...,len-1] 是Strobogrammatic数,那么 s [ 1 , . . . , l e n 2 ] s[1,...,len-2] 必然也是Strobogrammatic数。而对于base case,很显然 n = 0 n=0 时Strobogrammatic数就只有一个空串 ( " " ) ("") n = 1 n=1 时Strobogrammatic数为 ( " 0 " , " 1 " , " 8 " ) ("0","1","8") 。接下来就可以用递归解决。想要求长度为 n n 的数,我们可以先得到长度为 n 2 n-2 的数,然后首尾加上中心对称的两个数即可,即,前后分别加 ( 1 , 1 ) , ( 6 , 9 ) , ( 8 , 8 ) , ( 9 , 6 ) (1,1),(6,9),(8,8),(9,6) 。由于开头不能有 0 0 ,所以我们在递归的时候还需要将 n n 作为参数传递进去,如果正在求比 n n 短的数,那么前后还可以加 0 0 ,也就是形成 " 0 " + s + " 0 " "0"+s+"0" ,这样在求长度为 n n 的数的时候不会再加上开头零。代码如下:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    /**
     * @param n: the length of strobogrammatic number
     * @return: All strobogrammatic numbers
     */
    public List<String> findStrobogrammatic(int n) {
        // write your code here
        return strobog(n, n);
    }
    // 作用是,返回已知最终要求m位的Strobogrammatic数的情况下,
    // 所需要求的所有n位Strobogrammatic数
    private List<String> strobog(int n, int m) {
    	// 如果长度为0或1,这是base case可以直接返回
        if (n == 0) {
            return new ArrayList<>(Arrays.asList(""));
        }
        if (n == 1) {
            return new ArrayList<>(Arrays.asList("0", "1", "8"));
        }
    	// 接下来先取得长度少了2的Strobogrammatic数
        List<String> shorter = strobog(n - 2, n), res = new ArrayList<>();
        for (int i = 0; i < shorter.size(); i++) {
            String s = shorter.get(i);
            // 如果最终要求长度为m的数,而现在正在求的数的长度n比m小,那么前后可以加0,
            // 因为在返回到n = m那一层的时候前后是不能加0,否则会造成有开头零,所有这里需要判断一下
            if (n < m) {
                res.add("0" + s + "0");
            }
            res.add("1" + s + "1");
            res.add("6" + s + "9");
            res.add("8" + s + "8");
            res.add("9" + s + "6");
        }
    
        return res;
    }
}

时间复杂度 O ( n 2 n ) O(n2^n) ,空间复杂度 O ( n ) O(n) n n 为长度。

发布了388 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105355879