LeetCode 698. Partition to K Equal Sum Subsets (划分为k个相等的子集)
题目标签:Dynamic Porgramming
首先来看看 sum 能不能被 k 整除, 不行直接return false;
接着 求出subset 的sum,再排序 nums 从小到大,从最后一个最大的数字开始遍历;
如果最大的数字,大于 subset 的sum,直接 return false;
然后把 有等于 subset sum 的 数字都过滤掉,剩下的数字就是 需要利用 递归 来判断的:
把 subsets 分为 过滤后的 新的 k 组;
从最大数字 开始 递归,每次试着把数字放入 subset,更新 subset;
当所有数字都放完之后,成功;
当试完所有可能性后,数字没有放完,失败。
具体看code。
Java Solution:
Runtime: 30 ms, faster than 21.47%
Memory Usage: 38.6 MB, less than 9.30%
完成日期:5/2/2020
关键点:递归
class Solution { public boolean canPartitionKSubsets(int[] nums, int k) { int sum = sum(nums); // check if possible to have K equal sum subsets if(sum % k != 0) { return false; } int subSum = sum / k; Arrays.sort(nums); int beginIndex = nums.length - 1; // check if the largest num is greater than subSum if(nums[beginIndex] > subSum) { return false; } // check if any num is equal to subSum, no need to pass them into recursion while (beginIndex >= 0 && nums[beginIndex] == subSum) { beginIndex--; k--; } // pass it into recursion return partition(new int[k], nums, beginIndex, subSum); } private boolean partition(int[] subsets, int[] nums, int index, int target) { if(index < 0) { return true; } int selected = nums[index]; // iterate each subset for(int i = 0; i < subsets.length; i++) { // if possible, put selected number into the subset if(subsets[i] + selected <= target) { subsets[i] += selected; if(partition(subsets, nums, index - 1, target)) { return true; } subsets[i] -= selected; } } return false; } private int sum(int[] nums) { int sum = 0; for(int n : nums) { sum += n; } return sum; } }
参考资料:https://www.youtube.com/watch?v=8XEcEYsG6Ck
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/