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.

Approach #1: DFS + Backtracking. [C++]

class Solution {
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
int len = nums.size();
if (k == 1) return true;
if (len < k) return false; int sum = 0;
for (int num : nums)
sum += num;
if (sum % k != 0) return false; int avg = sum / k;
vector<int> token(len+5, 0), subsets(k+5, 0);
subsets[0] = nums[len-1];
token[len-1] = 1;
return solve(nums, token, subsets, avg, k, len, 0, len-1);
} private:
bool solve(vector<int>& nums, vector<int>& token, vector<int>& subsets,
const int& avg, const int& k, const int& len, int curIdx, int limitIdx) {
if (subsets[curIdx] == avg) {
if (curIdx == k-2) return true;
return solve(nums, token, subsets, avg, k, len, curIdx+1, len-1);
} for (int i = limitIdx; i >= 0; --i) {
if (token[i] == 1) continue;
int tmp = subsets[curIdx] + nums[i]; if (tmp <= avg) {
subsets[curIdx] += nums[i];
token[i] = 1;
bool nxt = solve(nums, token, subsets, avg, k, len, curIdx, i-1);
subsets[curIdx] -= nums[i];
token[i] = 0;
if (nxt) return true;
}
} return false;
}
};

  

Analysis:

We can solve this problem recursively, we keep an array for sum of each partition and a array to check whether an element is already taken into some partition or not.

First we need to check some base cases:

If K is 1, then we already have our answer, complete array is only sbset with same sum.

If N < K, then it is not possible to divide array into subsets with equal sum, because we can't divide the array into more than N parts.

If sum of array is not divisible by K. then it is not possible to divide the array. We will proceed only if k divides sum. Our goal reduces to divide array into K parts where sum of each part should be array_sum / k

In above code  a recursive method is written which tries to add array element into some subset. If sum of this subset reaches required sum, we iterator for next part recursively, otherwise we backtrack for different set of elements. If number of subsets whose sum reaches the required sum is (K-1), we flag that it is possible to partition array nto K parts with equal sum, because remaining elements already have a sum equal to required sum.

Reference:

https://www.geeksforgeeks.org/partition-set-k-subsets-equal-sum/

698. Partition to K Equal Sum Subsets的更多相关文章

  1. 【LeetCode】698. Partition to K Equal Sum Subsets 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 日期 题目地址:https://leetco ...

  2. 698. Partition to K Equal Sum Subsets 数组分成和相同的k组

    [抄题]: Given an array of integers nums and a positive integer k, find whether it's possible to divide ...

  3. [LeetCode] 698. Partition to K Equal Sum Subsets

    Problem Given an array of integers nums and a positive integer k, find whether it's possible to divi ...

  4. 【leetcode】698. Partition to K Equal Sum Subsets

    题目如下: 解题思路:本题是[leetcode]473. Matchsticks to Square的姊妹篇,唯一的区别是[leetcode]473. Matchsticks to Square指定了 ...

  5. [LeetCode] Partition to K Equal Sum Subsets 分割K个等和的子集

    Given an array of integers nums and a positive integer k, find whether it's possible to divide this ...

  6. LeetCode Partition to K Equal Sum Subsets

    原题链接在这里:https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/ 题目: Given an arr ...

  7. 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 ...

  8. [Swift]LeetCode698. 划分为k个相等的子集 | 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 ...

  9. HDU-3280 Equal Sum Partitions

    http://acm.hdu.edu.cn/showproblem.php?pid=3280 用了简单的枚举. Equal Sum Partitions Time Limit: 2000/1000 M ...

随机推荐

  1. 【原创】Silverlight之TextBox的LostFocus、GotFocus事件

    <TextBox x:Name="txtCount" Width="200" Height="35" GotFocus="t ...

  2. css样式: 宽高按一定比例进行自适应

    纯 CSS 实现高度与宽度成比例的效果 最近在做一个产品列表页面,布局如右图所示.页面中有若干个 item,其中每个 item 都向左浮动,并包含在自适应浏览器窗口宽度的父元素中. item 元素的 ...

  3. Python3编程技巧

    高效处理数据类型方法: In []: from random import randint In []: data=[randint(-,) )] In []: data Out[]: [-, -, ...

  4. tp5允许跨域

    header("Access-Control-Allow-Origin: *"); 放在命名空间之后

  5. W-D-S-UART编程

    1.协议原理 2.原理框图 3.开发板底板与核心板图 4.开始配置寄存器 a).使相应I/O引脚配置为UART引脚 b).配置数据发送模式 c).设置为中断或查询模式 d).使能串口缓存 e).流量控 ...

  6. linux 静态链接库demo

    目录结构 ./main.c        #include<stdio.h> #include "./lib/jtlib1.h" int main() {     pr ...

  7. Spring Boot 集成 Mybatis(druid 数据库连接池 以及 分页配置)

    MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射,目前很大一部分互联网.软件公司都在使用这套框架 关于Mybatis-Generator的下载可以到这个地址:http ...

  8. 2018.09.02 bzoj1296: [SCOI2009]粉刷匠(dp套dp)

    传送门 dp好题. 先推出对于每一行花费k次能最多粉刷的格子数. 然后再推前i行花费k次能最多粉刷的格子数. 代码: #include<bits/stdc++.h> #define N 5 ...

  9. Django模型层(1)

    https://www.cnblogs.com/yuanchenqi/articles/8933283.html MVC或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦, ...

  10. Django入门与实践 17-26章总结

    Django入门与实践-第17章:保护视图 Django 有一个内置的视图装饰器 来避免它被未登录的用户访问: 现在如果用户没有登录,将被重定向到登录页面: 现在尝试登录,登录成功后,应用程序会跳转到 ...