题目地址:
https://www.lintcode.com/problem/strobogrammatic-number-ii/description
如果一个数,对其翻转 后与自己相等,那么就称此数为Strobogrammatic数。求所有长度为 的Strobogrammatic数。
容易知道,如果 是Strobogrammatic数,那么 必然也是Strobogrammatic数。而对于base case,很显然 时Strobogrammatic数就只有一个空串 , 时Strobogrammatic数为 。接下来就可以用递归解决。想要求长度为 的数,我们可以先得到长度为 的数,然后首尾加上中心对称的两个数即可,即,前后分别加 。由于开头不能有 ,所以我们在递归的时候还需要将 作为参数传递进去,如果正在求比 短的数,那么前后还可以加 ,也就是形成 ,这样在求长度为 的数的时候不会再加上开头零。代码如下:
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;
}
}
时间复杂度 ,空间复杂度 , 为长度。