We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 中等
Related Topics: 数组, 动态规划
给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
nums
示例 1:
输入:nums = [1,5,11,5] 输出:true 解释:数组可以分割成 [1, 5, 5] 和 [11] 。
示例 2:
输入:nums = [1,2,3,5] 输出:false 解释:数组不能分割成两个元素和相等的子集。
提示:
1 <= nums.length <= 200
1 <= nums[i] <= 100
Language: JavaScript
/** * @param {number[]} nums * @return {boolean} */ // dp[j] 中j代表背包容量,dp[j] 表示能找到的最接近背包容量j的和 // 外层循环表示当前放入的数,内层循环用来不断减小背包的容量求得不同容量下最接近背包容量的和 // 状态转移方程 // 最接近j的和 = Math.max(以前算出的最接近j的和,当前放入的数+最接近j-num[i]的和) // 即:dp[j] = Math.max(dp[j], nums[i]+dp[j-nums[i]]) var canPartition = function (nums) { let sum = nums.reduce((cur, pre) => cur + pre) if (sum % 2 !== 0) return false // 满足题意和必须能整除2 let dp = new Array(sum / 2 + 1).fill(0) for (let i = 0; i < nums.length; i++) { for (let j = sum / 2; j >= nums[i]; j--) { dp[j] = Math.max(dp[j], nums[i] + dp[j - nums[i]]) if (dp[j] === sum / 2) return true } } return false };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
416. 分割等和子集
Description
Difficulty: 中等
Related Topics: 数组, 动态规划
给你一个 只包含正整数 的 非空 数组
nums
。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。示例 1:
示例 2:
提示:
1 <= nums.length <= 200
1 <= nums[i] <= 100
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: