LeetCode---Perfect Squares、Longest Increasing Subsequence

279. Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example 1:

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

完全平方数

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

思路1:

四平方和定理,任何一个正整数都可以由4个整数的平方和组成。即对所有n,都有n=aa+bb+cc+dd。

也就是说,这个题目返回的答案只有1、2、3、4这四种可能。

推理1. 我们可以将输入的数字除以4来大大减少计算量,并不改变答案。

推理2. 一个数除以8的余数,如果余数为7, 则其必然由四个完全平方数组成。

推理3. 然后检测是否可以将简化后的数拆分为两个完全平方数,否则一定由三个完全平方数组成。
 

class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        import math
        while n%4==0:
            n=n//4
        if n%8==7:
            return 4
        if int(math.sqrt(n))**2==n:
            return 1
        i=1
        while i*i<=n:
            j=math.sqrt(n-i*i)
            if int(j)==j:
                return 2
            i+=1
        return 3

思路2:动态规划

维护一个长度为n+1的数组,第i位存储和为i的最少整数个数。则f(i)只与i之前的数组有关。

用dp[i]表示数字组成数字i的最少完美平方的个数, 状态转移方程

dp[i] = min(dp[i], dp[i - j*j] +1)
class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        dp=[n]*(n+1)
        dp[0]=0
        dp[1]=1
        for i in range(2,n+1):
            j=1
            while j*j<=i:
                dp[i]=min(dp[i],dp[i-j*j]+1)
                j+=1
        return dp[-1]

 300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

最长上升子序列

给定一个无序的整数数组,找到其中最长上升子序列的长度。

思路:使用动态规划。用Dp[i]来保存从0-i的数组的最长递增子序列的长度。如上数组Dp[0]=1,Dp[1]=1,Dp[2]=1,Dp[3]=2,Dp[4]=2。。。计算Dp[i]的值可以对Dp[i]之前数值进行遍历,如果nums[i]>nums[j],则Dp[i] = max(Dp[i],Dp[j]+1)。复杂度为O(n*n).

class Solution(object):
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:
            return 0
        n=len(nums)
        dp=[1]*n
        for i in range(n-1):
            for j in range(0,i+1):
                if nums[i+1]>nums[j]:
                    dp[i+1]=max(dp[i+1],dp[j]+1)
        return max(dp)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值