原题链接在这里: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"]
.
题解:
base case 分奇数偶数两种. 拿到base case, 在每一个 string 前后加上"1", "1"; "8","8";...等等添加到新的res中去.
corner case是若是string 长度大于1, "0"不能加在最前面. 所以用 m != n搞定.
Time Complexity: O(2^n). Space: O(n).
AC Java:
1 public class Solution { 2 public List<String> findStrobogrammatic(int n) { 3 return findHelper(n,n); 4 } 5 6 private List<String> findHelper(int m, int n){ 7 if(m == 0){ 8 return new ArrayList<String>(Arrays.asList("")); 9 } 10 if(m == 1){ 11 return new ArrayList<String>(Arrays.asList("0", "1", "8")); 12 } 13 List<String> base = findHelper(m-2, n); 14 List<String> res = new ArrayList<String>(); 15 for(String s : base){ 16 if(m != n){ 17 res.add("0" + s + "0"); 18 } 19 res.add("1" + s + "1"); 20 res.add("8" + s + "8"); 21 res.add("6" + s + "9"); 22 res.add("9" + s + "6"); 23 } 24 return res; 25 } 26 }
时间: 2024-12-15 08:40:30