边工作边刷题: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

原文地址:https://www.cnblogs.com/absolute/p/5815684.html