python_lintcode_697Check Sum of Square Numbers_114不同的路径

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][n]=[[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][-1]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值