zoukankan      html  css  js  c++  java
  • 栈和队列_leetcode279-经典的层次遍历

    #coding=utf-8
    #点评:
    #递归思想加层次遍历,很经典的解题模板思想 20181220



    class Solution(object):
    def numSquares(self, n):
    """
    :type n: int
    :rtype: int
    """

    pair = (n,0)
    queue = []
    queue.append(pair)

    while queue:
    curPair = queue.pop(0)
    num = curPair[0]
    step = curPair[1]

    if num == 0:
    return step

    for i in range(1,num+1):
    if num - i *i >= 0:
    nextPair = (num-i*i,step+1)
    queue.append(nextPair)
    else:
    break

    class Solution2(object):
    def numSquares(self, n):
    """
    :type n: int
    :rtype: int
    """
    pair = (n, 0)
    queue = []
    queue.append(pair)

    #matrix = [[0 for i in range(3)] for i in range(3)]
    visit = [0 for i in range(n+1)]
    visit[n] = 1

    while queue:
    curPair = queue.pop(0)
    num = curPair[0]
    step = curPair[1]

    if num == 0:
    return step


    for i in range(1, num + 1):
    nextNum = num - i*i
    if nextNum >= 0:
    if visit[nextNum] == 0:
    nextPair = (nextNum, step + 1)
    queue.append(nextPair)
    visit[nextNum] = 1
    else:
    break


    class Solution3(object):
    def numSquares(self, n):
    """
    :type n: int
    :rtype: int
    """
    pair = (n, 0)
    queue = []
    queue.append(pair)

    #matrix = [[0 for i in range(3)] for i in range(3)]
    visit = [0 for i in range(n+1)]
    visit[n] = 1

    while queue:
    curPair = queue.pop(0)
    num = curPair[0]
    step = curPair[1]

    if num == 0:
    return step


    for i in range(1, num + 1):
    nextNum = num - i*i
    if nextNum >= 0:
    if visit[nextNum] == 0:

    if nextNum == 0:
    return step+1

    nextPair = (nextNum, step + 1)
    queue.append(nextPair)
    visit[nextNum] = 1
    else:
    break



    # 动态规划
    class Solution4(object):
    def numSquares(self, n):

    return self.squareNum(n)

    def squareNum(self, n):

    self.memo = [n for i in range(n + 1)]

    self.memo[0] = 0
    self.memo[1] = 1

    # #memo[2]
    # for i in range(1, 2):
    # if n - i ** 2 >= 0:
    # self.memo[2] = min(self.memo[2],1+self.memo[n - i ** 2])
    #
    #
    # #memo[3]
    # for i in range(1, 3):
    # if n - i ** 2 >= 0:
    # self.memo[3] = min(self.memo[3],1+self.memo[n - i ** 2])



    for i in range(1,n+1):
    for j in range(1,i):
    if i - j ** 2 >= 0:
    self.memo[i] = min(self.memo[i], 1 + self.memo[i - j ** 2])


    return self.memo[n]s = Solution2()print s.numSquares(13)
  • 相关阅读:
    [bzoj4241] 历史研究 (分块)
    [tyvj2054] 四叶草魔杖 (最小生成树 状压dp)
    20180710 考试记录
    [luogu2047 NOI2007] 社交网络 (floyed最短路)
    [luogu2081 NOI2012] 迷失游乐园 (树形期望dp 基环树)
    [luogu1600 noip2016] 天天爱跑步 (树上差分)
    [luogu2216 HAOI2007] 理想的正方形 (2dST表 or 单调队列)
    [poj 3539] Elevator (同余类bfs)
    [BZOJ1999] 树网的核 [数据加强版] (树的直径)
    bzoj2301 [HAOI2011]Problem b
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10547443.html
Copyright © 2011-2022 走看看