边工作边刷题:70天一遍leetcode: day 75-2
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的更多相关文章
- 边工作边刷题:70天一遍leetcode: day 75
Group Shifted Strings 要点:开始就想到了string之间前后字符diff要相同. 思维混乱的地方:和某个string的diff之间是没有关系的.所以和单个string是否在那个点 ...
- 边工作边刷题:70天一遍leetcode: day 89
Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...
- 边工作边刷题:70天一遍leetcode: day 77
Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...
- 边工作边刷题:70天一遍leetcode: day 78
Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...
- 边工作边刷题:70天一遍leetcode: day 85-3
Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...
- 边工作边刷题:70天一遍leetcode: day 101
dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...
- 边工作边刷题:70天一遍leetcode: day 1
(今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...
- 边工作边刷题:70天一遍leetcode: day 70
Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...
- 边工作边刷题:70天一遍leetcode: day 71-3
Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...
- 边工作边刷题:70天一遍leetcode: day 71-2
One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...
随机推荐
- 线段树或树状数组---Flowers
题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=4325 Description As is known to all, the blooming tim ...
- isEmpty与null、""的区别
前一段时间我阅读别人的代码,发现有的时候用isEmpty,有的时候用null,有的时候用"".我很困惑三者之间的区别,于是我就自己写了一个程序来验证一下 public class ...
- Ahjesus获取自定义属性Attribute或属性的名称
1:设置自己的自定义属性 public class NameAttribute:Attribute { private string _description; public NameAttribut ...
- SharePoint 2013 设置自定义布局页
在SharePoint中,我们经常需要自定义登陆页面.错误页面.拒绝访问等:不知道大家如何操作,以前自己经常在原来页面改或者跳转,其实SharePoint为我们提供了PowerShell命令,来修改这 ...
- C#获取本地系统日期格式
我们可以通过使用DataTime这个类来获取当前的时间.通过调用类中的各种方法我们可以获取不同的时间:如:日期(2008-09-04).时间(12:12:12).日期+时间(2008-09-04 12 ...
- 利用Android多进程机制来分割组件
android对于内存有一定的限制,很多手机上对内存的限制是完全不同的.我们的应用程序其实就是一个进程,这个进程是完全独立的,这个进程分配的内存是一定的,所以我们经常会遇到OOM的问题.但,你可能不知 ...
- Linux useful command
查看linux系统里面的各个目录.文件夹的大小和使用情况, 先切换到需要查看的目录,如果需要查看所有linux目录的使用情况就直接切换到系统跟目录,然后执行: du -h --max-depth=1 ...
- IOS 应用跳转 (IOS9白名单)
跳转到指定app的实现 IOS中应用的跳转是通过URL实现的,因此在实现应用跳转之前我们要设置一下对应的URL. 图一(寻找配置软件的URL) 图二(具体配置选项) 注意: 如果IOS版本为IOS9 ...
- [VMware]设置VM虚拟机随系统自动启动
设置步骤: 1.找到VM的安装路径,右键vmware发送到桌面快捷方式 2.右键桌面快捷方式的属性,看到目标的属性框 3.找到需要自启动的虚拟机路径,如: D:\QC_VM\Clone of Wind ...
- EF+MVC+cod First项目性能优化总结
1.EF:this.Configuration.UseDatabaseNullSemantics = true; //关闭数据库null比较行为 2.实体必填字段要加:[Required]属性,可定长 ...