Strobogrammatic Number I/II/III

要点:记题,注意轴对称和点对称的区别。这题就是几个固定digit之间的palindrome

I

https://repl.it/CqLu

II

https://repl.it/CivO (java)

https://repl.it/CqKC (python)

  • 外循环中止条件:2个或3个字符都是循环一次,每层n-2,所以是n>1
  • 00不考虑的情况是n>3,因为是从内向外循环,2或者3是最外一层
  • python: string可以unpack为单一char,但是变量个数必须和len(string)一样

III

https://repl.it/CkFM/2 (python iterate all results,只能beat 19.05%,懒得看快的方法了 https://discuss.leetcode.com/topic/50073/python-46ms-96-77-without-generating-all-the-numbers)

  • II中的recursion就是从最短开始build到某个长度,而题的目标就是找到在low和high长度之间]的所有。所以不用外层的loop,单一的recursion就够。递归的过程就是不断增加长度,所以中途检查是不是在low/high的长度范围,同时是不是value在范围内
  • positive and negative conditions:
    • no positive as you keep counting until all paths fail,
    • negative: two conditions:
      • if len(path)+2>high.size() (every round you add two chars) or
      • == but >int(high)
  • 落入[low,high]之间的都有机会++res,另外need to eliminate two ‘0’ at outmost layer (unlike II, to simplify, still can recurse into it and just don’t count it)
  • 中止条件:(1) >high.size() (比low小为什么也return呢?)(2) 等于high.size()但值超过
  • string表示的数比较不要慌,python简单搞定int()
# A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

# Write a function to determine if a number is strobogrammatic. The number is represented as a string.

# For example, the numbers "69", "88", and "818" are all strobogrammatic.

# Hide Company Tags Google
# Hide Tags Hash Table Math
# Hide Similar Problems (M) Strobogrammatic Number II (H) Strobogrammatic Number III class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
umap = {'1':'1', '8':'8', '6':'9', '9':'6', '0':'0'}
mid = ['1', '8', '0']
i,j = 0, len(num)-1
if len(num)>1 and num[0]=='0': return False
while i<=j:
if i==j:
return num[i] in mid
else:
if num[i] not in umap or umap[num[i]]!=num[j]:
return False
i+=1
j-=1
return True
import java.util.*;
class Main {
public static void main(String[] args) {
Solution sol = new Solution();
List<String> res = sol.findStrobogrammatic(5); for(String s : res) {
System.out.println(s);
}
}
} class Solution {
public List<String> findStrobogrammatic(int n) {
int[] nums = new int[]{1,8,6,9};
List<String> solutions = new ArrayList<>();
StringBuilder sb = new StringBuilder();
stroboHelper(nums, 0, n/2, sb, solutions); // List<String> res = new ArrayList<>();
// for(String s : solutions) { // }
return solutions;
} void stroboHelper(int[] nums, int start, int n, StringBuilder sb, List<String> solutions) {
if(start==n) {
solutions.add(sb.toString());
return;
} for(int i : nums) {
sb.append(Integer.toString(i));
stroboHelper(nums, start+1, n, sb, solutions);
sb.setLength(sb.length()-1);
}
}
}
# 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"]. # Hint: # Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
# Hide Company Tags Google
# Hide Tags Math Recursion
# Hide Similar Problems (E) Strobogrammatic Number (H) Strobogrammatic Number III class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
umap = {'1':'1', '8':'8', '6':'9', '9':'6', '0':'0'}
mid = ['1', '8', '0']
def helper(n, res, solutions):
if n<=0:
if not n and (len(res)==1 or res[0]!='0'):
solutions.append(res)
return for k in umap.keys():
helper(n-2, k+res+umap[k], solutions) solutions = []
if n%2==1:
for i in mid:
helper(n-1, i, solutions)
else:
helper(n, "", solutions)
return solutions sol = Solution()
assert sol.findStrobogrammatic(2)==["11","88","96","69"]
assert sol.findStrobogrammatic(1)==["1","8","0"]
# A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

# Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.

# For example,
# Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers. # Note:
# Because the range might be a large number, the low and high numbers are represented as string. # Hide Tags Math Recursion
# Hide Similar Problems (E) Strobogrammatic Number (M) Strobogrammatic Number II class Solution(object):
def strobogrammaticInRange(self, low, high):
"""
:type low: str
:type high: str
:rtype: int
"""
umap = {'1':'1', '8':'8', '6':'9', '9':'6', '0':'0'}
mid = ['', '1', '8', '0']
self.count = 0
def helper(low, high, res):
l = len(res)
if len(low) <= l <= len(high):
if l==len(high) and int(res)>int(high): return
if int(res)>=int(low) and (l==1 or res[0]!='0'):
self.count+=1
#print res if l+2 > len(high):
return for k in umap.keys():
helper(low, high, k+res+umap[k]) solutions = []
for m in mid:
helper(low, high, m) return self.count sol = Solution()
assert sol.strobogrammaticInRange("50","100")==3
assert sol.strobogrammaticInRange("12","1200")==17

边工作边刷题:70天一遍leetcode: day 75-2的更多相关文章

  1. 边工作边刷题:70天一遍leetcode: day 75

    Group Shifted Strings 要点:开始就想到了string之间前后字符diff要相同. 思维混乱的地方:和某个string的diff之间是没有关系的.所以和单个string是否在那个点 ...

  2. 边工作边刷题:70天一遍leetcode: day 89

    Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...

  3. 边工作边刷题:70天一遍leetcode: day 77

    Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...

  4. 边工作边刷题:70天一遍leetcode: day 78

    Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...

  5. 边工作边刷题:70天一遍leetcode: day 85-3

    Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...

  6. 边工作边刷题:70天一遍leetcode: day 101

    dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...

  7. 边工作边刷题:70天一遍leetcode: day 1

    (今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...

  8. 边工作边刷题:70天一遍leetcode: day 70

    Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...

  9. 边工作边刷题:70天一遍leetcode: day 71-3

    Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...

  10. 边工作边刷题:70天一遍leetcode: day 71-2

    One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...

随机推荐

  1. 【Java Saves!】Session 6:十六指星人

    前面说,计算机用2个手指头数数,它内部的数是二进制,有0和1两个数字.也看到,对于人来说,二进制数too long, too inconvenient, sometimes troublesome.程 ...

  2. (旧)子数涵数·DW——网页制作的流程

    PS:这是我很早以前的一个废掉的项目. 当时用的还是table排版,现在基本都是div了吧. 这个项目前段时间,我还抢救过一次,后来还是放弃了. 先行.网页制作的流程分为哪些呢? 一.网站策划(当时, ...

  3. [小北De编程手记] : Lesson 06 - Selenium For C# 之 流程控制

    无论你是用哪一种自动化测试的驱动框架,当我们构建一个复杂应用程序的自动化测试的时候.都希望构建一个测试流程稳定,维护成本较低的自动化测试.但是,现实往往没有理想丰满.而这一篇,我会为大家讲解我们在使用 ...

  4. ES6新特性(函数默认参数,箭头函数)

    ES6新特性之 函数参数的默认值写法 和 箭头函数. 1.函数参数的默认值 ES5中不能直接为函数的参数指定默认值,只能通过以下的变通方式:   从上面的代码可以看出存在一个问题,当传入的参数为0或者 ...

  5. C# DevExpress 的gridControl或gridView数据导出失败解决方法

    来自:http://blog.csdn.net/lybwwp/article/details/8049464 谢谢 在使用DevExpress 的GridPanel控件的时候出现了一个莫名其妙的现象, ...

  6. Snort - manual 笔记(三)

    1.6 Reading pcap files Snort 不仅可以监听interface, 还可以读取和分析已经捕获的数据包. 1.6.1 Command line arguments 下面的命令都可 ...

  7. 穷举法破解 zebrone1.1

    系统 : Windows xp 程序 : zebrone1.1 程序下载地址 :http://pan.baidu.com/s/1boqVcU7 要求 : 编写注册机 使用工具 :OD 可在看雪论坛中查 ...

  8. 文件快速搜索工具-Everything的使用(转)

    首先它是一款基于名称实时定位文件和目录的搜索工具,有以下几个优点: 快速文件索引 快速文件搜索 较低资源占用 轻松分享文件索引 实时跟踪文件更新 通过使用everything小工具,可以提高我们的工作 ...

  9. 安卓开发--android library projects cannot be launched错误

    最新因为学习,问技术友要了几个源代码,导入源代码的时候无法进行真机或者虚拟机测试. 原因:android library projects cannot be launched 百度了一下,解决方法很 ...

  10. IOS杂笔- 7(类方法load与initialize的区别 浅析)

    在介绍两种类方法之前,NSObject Class Reference里对这两个方法说明: +(void)initialize The runtime sends initialize to each ...