Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1782211
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2016-03-28 15:50:18

Item 1:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

很简单的stack的应用,代码如下:

点击(此处)折叠或打开

  1. def item1(astr):
  2.     #astr: a string compose of "(){}[]"
  3.     ll=[]
  4.     index=0
  5.     balanced=True
  6.     while index < len(astr) and balanced:
  7.         ch=astr[index]
  8.         if ch in "([{":
  9.             ll.append(ch)
  10.         else:
  11.             if len(ll)==0:
  12.                 balanced=False
  13.             else:
  14.                 top=ll.pop()
  15.                 if not matches(top,ch):
  16.                     balanced=False
  17.         index+=1
  18.     if balanced and len(ll)==0:
  19.         return True
  20.     else:
  21.         return False

  22. def matches(open,close):
  23.     opens="([{"
  24.     closes=")]}"
  25.     return opens.index(open)==closes.index(close)


  26. print(item1('{{([][])}()}'));
  27. print(item1('[{()]'));

Item 2: Additive number

Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

For example:
"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.

1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.

1 + 99 = 100, 99 + 100 = 199

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.


这个我没有写出来,参照别人的来学习一下,只是把类改成了函数而已。
http://bookshadow.com/weblog/2015/11/18/leetcode-additive-number/

点击(此处)折叠或打开

  1. def isAdditiveNum(num):
  2.     #num: a number
  3.     k=str(num)
  4.     n=len(k)
  5.     for i , j in itertools.combinations(range(1,n),2):
  6.         a,b=k[:i],k[i:j]
  7.         if a!=str(int(a)) or b != str(int(b)):
  8.             continue
  9.         while j < n:
  10.             c=str(int(a)+int(b))
  11.             if not k.startswith(c,j):
  12.                 break
  13.             j+=len(c)
  14.             a,b=b,c
  15.         if j==n:
  16.             return True
  17.     return False

  18. print(isAdditiveNum(112358))
  19. print(isAdditiveNum(199100199))

  20. def isAdditiveNum2(num):
  21.     #num:a number
  22.     k=str(num)
  23.     def isValid(astr):
  24.         #astr: string
  25.         return len(astr)==1 or astr[0]!='0'

  26.     def search(a,b,c):
  27.         d=str(int(a)+int(b))
  28.         if not isValid(d) or not c.startswith(d):
  29.             return False
  30.         if c==d:
  31.             return True
  32.         return search(b,d,c[len(d):])

  33.     size=len(k)
  34.     for x in range(1,size//2+1):
  35.         for y in range(x+1,size):
  36.             a,b,c=k[:x],k[x:y],k[y:]
  37.             if not isValid(a) or not isValid(b):
  38.                 continue
  39.             if search(a,b,c):
  40.                 return True
  41.     return False



  42. print(isAdditiveNum2(112358))
  43. print(isAdditiveNum2(199100199))

Item 3:

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

解法可以直接参考:

点击(此处)折叠或打开

  1. def longestIncreasingPath(matrix):
  2.     #matrix: List[List[int]]
  3.     #rtype: int
  4.     if not matrix: return 0
  5.     m,n=len(matrix),len(matrix[0])
  6.     dis=[ [0] * n for i in range(m)]
  7.     return max([dfs(i,j,m,n,matrix,dis) for j in range(n) for i in range(m)])

  8. def dfs(x,y,m,n,matrix,dis):
  9.     if dis[x][y]: return dis[x][y]
  10.     for dx,dy in ([(1,0),(-1,0),(0,1),(0,-1)]):
  11.         nx,ny=x+dx,y+dy
  12.         if nx>=0 and nx<m and ny>=0 and ny<n and matrix[x][y]<matrix[nx][ny]:
  13.             dis[x][y]=max(dis[x][y],dfs(nx,ny,m,n,matrix,dis))
  14.     dis[x][y]+=1
  15.     return dis[x][y]

  16. exp1=[[9,9,4],
  17.       [6,6,8],
  18.       [2,1,1]]

  19. exp2=[[3,4,5],
  20.       [3,2,6],
  21.       [2,2,1]]
  22.       

  23. #print(longestIncreasingPath(exp1))
  24. #print(longestIncreasingPath(exp2))

  25. import operator
  26. def longestIncreasingPath2(matrix):
  27.     #matrix: List[List[int]]
  28.     #rtype: int
  29.     h=len(matrix)
  30.     if h==0 : return 0
  31.     w=len(matrix[0])
  32.     dp=[[1]*w for i in range(h)]
  33.     slist=sorted([(i,j,val)
  34.             for i,row in enumerate(matrix)
  35.             for j,val in enumerate(row)],
  36.             key=operator.itemgetter(2))
  37.     for x,y,val in slist:
  38.         for dx,dy in zip([1,0,-1,0],[0,1,0,-1]):
  39.             nx,ny=x+dx,y+dy
  40.             if h>nx>=0 and w>ny>=0 and matrix[nx][ny] > matrix[x][y]:
  41.                 dp[nx][ny]=max(dp[nx][ny],dp[x][y]+1)
  42.     return max([max(x) for x in dp])

  43. exp1=[[9,9,4],
  44.       [6,6,8],
  45.       [2,1,1]]

  46. exp2=[[3,4,5],
  47.       [3,2,6],
  48.       [2,2,1]]


  49. print(longestIncreasingPath2(exp1))
  50. print(longestIncreasingPath2(exp2))


阅读(1403) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~