698. Partition to K Equal Sum Subsets
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了698. Partition to K Equal Sum Subsets相关的知识,希望对你有一定的参考价值。
问题描述:
Given an array of integers nums
and a positive integer k
, find whether it‘s possible to divide this array into k
non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 Output: True Explanation: It‘s possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Note:
1 <= k <= len(nums) <= 16
.0 < nums[i] < 10000
.
解题思路:
首先我们要确定当前数组的和能分整除k,若不能整除k,则直接返回false。若能够整除,则可以进一步检查能否分成这些部分。
可以用dfs来解答。
需要用一个visited数组来记录是否已经用过这个数字。
用k来表示还剩多少部分, start 表示从哪里开始找,target表示目标和,cur_sum表示当前和。
代码:
DFS解法:
class Solution { public: bool canPartitionKSubsets(vector<int>& nums, int k) { if(nums.empty()) return false; int sum = 0; for(int i : nums){ sum += i; } if(sum % k != 0) return false; vector<bool> visited(nums.size(), false); return canPartition(nums, visited, 0, k, 0, sum/k); } bool canPartition(vector<int> &nums, vector<bool> &visited, int start, int k, int cur_sum, int target){ if(k == 1) return true; if(cur_sum == target) return canPartition(nums, visited, 0, k-1, 0, target); for(int i = start; i < nums.size(); i++){ if(!visited[i]){ visited[i] = true; if(canPartition(nums,visited, i+1, k, cur_sum+nums[i], target)) return true; visited[i] = false; } } return false; } };
以上是关于698. Partition to K Equal Sum Subsets的主要内容,如果未能解决你的问题,请参考以下文章
python https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/
Partition of a set into K subsets with equal sum
leetcode_easy_array1013. Partition Array Into Three Parts With Equal Sum
LeetCode 663. Equal Tree Partition