您的位置:首页 > 编程语言 > Python开发

python_lintcode_697Check Sum of Square Numbers_114不同的路径

2017-10-07 18:59 489 查看

697Check Sum of Square Numbers

题目

http://www.lintcode.com/zh-cn/problem/check-sum-of-square-numbers/

Given a integer c, your task is to decide whether there’re two integers a and b such that a^2 + b^2 = c.

样例

Given n = 5

Return true // 1 * 1 + 2 * 2 = 5

Given n = -5

Return false

思路

若用嵌套两个for,容易在49%时,num=400000006出现Time Limit Exceeded

代码

import math
class Solution:
"""
@param: : the given number
@return: whether whether there're two integers
"""

def checkSumOfSquareNumbers(self, num):
# write your code here
if num==1 or num==0:return True
if num<0:return False
for i in range(int(math.sqrt(num))+1):
pd=math.sqrt(num-i**2)
if pd == int(pd):return True
return False


该博客多种解法:http://blog.csdn.net/huanghanqian/article/details/77579809

114不同的路径

题目

http://www.lintcode.com/zh-cn/problem/unique-paths/

有一个机器人的位于一个 m × n 个网格左上角。

机器人每一时刻只能向下或者向右移动一步。机器人试图达到网格的右下角。

问有多少条不同的路径?

注意事项

n和m均不超过100

您在真实的面试中是否遇到过这个题? Yes

样例

给出 m = 3 和 n = 3, 返回 6.

给出 m = 4 和 n = 5, 返回 35.

思路

用到动态规划dp[i][j]=dp[i-1][j]+dp[i][j-1]

新建一个dp[m]
=[[1 1 1 1 1…]…..[1 1 1 1 1…]]

然后从1->m和1->n都dp[i][j]=dp[i-1][j]+dp[i][j-1],比如dp[1][1],它可以从dp[1][0]和dp[0][1]过来,则有两种路径,同理当dp[1][2]可以从dp[1][1]和dp[0][2]过来,则有三种路径.

当m=3,n=8
0   1   2   3   4   5   6       7
0   1   1   1   1   1   1   1       1
1   1   2   3   4   5   6   7       8
2   1   3   6   10  15  21  28      36
则有36种路径


代码

class Solution:
"""
@param: m: positive integer (1 <= m <= 100)
@param: n: positive integer (1 <= n <= 100)
@return: An integer
"""
def uniquePaths(self, m, n):
# write your code here
#m为行,n为列
dp  = [[1 for col in range(n)] for row in range(m)]
for i in range(1,m):
for j in range(1,n):
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[-1<
97ff
/span>][-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: