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]
相关文章推荐
- lintCode(114)——不同的路径
- python_lintcode_115不同的路径 II_112删除排序链表中的重复元素
- lintcode-114-不同的路径
- Lintcode 114.不同的路径
- lintcode-不同的路径-114
- 不同环境中添加python默认的搜索路径
- 不同的路径-lintcode
- python 不同OS上的路径转换
- [Python]linux python解释器路径不同写法的区别
- [LintCode 376] 二叉树的路径和(Python)
- lintCode(115)——不同的路径||
- LintCode_不同的路径
- [Python]linux python解释器路径不同写法的区别
- lintcode-115-不同的路径 II
- lintcode 不同路径
- 不同的路径 II-LintCode
- Python递归输出字典所有不同深度的路径
- python 引入不同路径的module
- LintCode :不同的路径
- 小白的Python之路 day4 不同目录间进行模块调用(绝对路径和相对路径)