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


    s = Solution2()

    print s.numSquares(13)
  • 相关阅读:
    字符串初始化、查找字符+获取字符
    冒泡排序
    JAVA中值类型和引用类型的不同?
    二维数组初始化,属性,遍历,输出各元素总和。
    数组定义属性遍历循环,输出最大数
    for穷举,叠代练习
    HTML--Boby部分之<a>标签
    HTML--Boby内标签之多行文本及下拉框
    HTML--Boby部分Input之重置
    HTML--Boby部分Input之上传文件
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546545.html
Copyright © 2011-2022 走看看