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. ReactNative——生命周期

    1.创建阶段 getDefaultProps:处理props的默认值 在react.createClass调用 //在创建类的时候被调用 this.props该组件的默认属性 2.实例化阶段 Reac ...

  2. jetty加载spring-context容器源码分析

    带着疑问开始 web.xml的顺序问题 先拿一个最简单的spring mvc web.xml来说问题,如下图:如果我将三者的顺序倒置或是乱置,会产生什么结果呢? 启动报错?还是加载未知结果?还是毫无影 ...

  3. 为什么不推崇复杂的ORM

    上一篇文章写完,回复的人很多,有的说的很中肯,有的貌似只是看到文章的标题就进来写评论的!还有人问为什么我要屏蔽掉[反对]按钮,因为谁写文章都是为了分享,都在说出自己的心得体会.不过由于大家遇到的项目, ...

  4. [Intellij] 编译报错 javacTask

    报错信息: Idea 编译报错 javacTask: 源发行版 1.6 需要目标发行版 1.6 解决方案:

  5. TCP中close和shutdown之间的区别

    该图片截取自<<IP高效编程-改善网络编程的44个技巧>>,第17个技巧.  如果想验证可以写个简单的网络程序,分别用close和shutdown来断开连接,然后用tcpdum ...

  6. Git的安装和使用记录

    Git是目前世界上最先进的分布式版本控制系统(没有之一),只用过集中式版本控制工具的我,今天也要开始学习啦.廖雪峰的git教程我觉得很详细了,这里记录一下步骤以及我终于学会用Markdown了,真的是 ...

  7. 使用WebMatrix发布网站

    使用WebMatrix发布网站 WebMatrix 简介: Microsoft WebMatrix 是微软最新的 Web 开发工具,它包含了构建网站所需要的一切元素.您可以从开源 Web 项目或者内置 ...

  8. 上载EXCEL到SAP系统的方法之一

    TEXT_CONVERT_XLS_TO_SAP实例 使用:gui_upload去上传excel数据,每次都出现乱码,不管中文英文都乱码. 至今不知道gui_upload是否支持excel文件上传,. ...

  9. UISlider显示进度(并且实现图片缩放)

    图片展示效果如下: 其他没什么好说的,直接上代码: RootView.h: #import <UIKit/UIKit.h> @interface RootView : UIView @pr ...

  10. Python学习 windows下面安装Python和pip(一)

    windows下面安装Python和pip 安装Python 第一步,我们先来安装Python, https://www.python.org/downloads/ 这里选择的是2.7.10 第二步. ...