赞
踩
416、分割等和子集:
- class Solution(object):
- def canPartition(self, nums):
- """
- :type nums: List[int]
- :rtype: bool
- """
- sum_nums = sum(nums)
- if sum_nums % 2 != 0:
- return False
- target = sum_nums / 2
- dp = [0] * (target + 1)
- for i in range(len(nums)):
- for j in range(target, nums[i]-1, -1):
- dp[j] = max(dp[j], dp[j - nums[i]] + nums[i])
- return dp[target] == target
学习了01背包问题的二维解法和一维解法,一维解法是对二维解法的状态压缩,本质上仍是二维,遍历顺序和二维也不太一样,物品是正序遍历,背包是逆序遍历,初始化决定了dp数组走向是否正确,本题的应用思路是把target看成是背包容积,nums数组里的元素看成是一个个物品
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。