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. golang协程进行同步方法

    1.使用chanel func main() { done := make(chan bool) ticker := time.NewTicker(time.Millisecond * 1000) g ...

  2. swagger ui js 错误:Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'.

    经过排查,引发此错误的原因是,表中有一个字段名称为“NodeName”,应该是在前台xml解析时引发冲突所致.我的解决办法是: 修改列名,修改映射. 如下: [Column("NodeNam ...

  3. hook进程

    https://www.cnblogs.com/Leo_wl/p/3311279.html https://blog.csdn.net/u013761036/article/details/65465 ...

  4. eclipse新建web项目,发布 run as 方式和 new server然后添加项目方式。 后者无法自动编译java 成class文件到classes包下。

    eclipse新建web项目,发布 run as 方式和 new server然后添加项目方式. 后者无法自动编译java 成class文件到classes包下. 建议使用run as  -  run ...

  5. 常用C字符串函数

    static void str_repalce(char *src,char *from,char *to) {     char *p,*q;     int lenFrom;     int le ...

  6. KbmMW 服务器架构简介

    kbmmw 由于文档比较少,很多同学开始用时很难理解.一直准备写一个关于kbmmw 架构的东西. 这几天与红鱼儿(blog)研究服务器线程时,整理了一下,大概画了一下kbmmw (版本4.5)服务器的 ...

  7. shell的基本语法

    一 赋值运算符 1 += :使用方法是,((x+=需要增加的数字))算和值. 2 *=  :使用方法是,((x*=需要怎加的倍数))算乘值. 3 %= :使用方法是,((x%=需要除以的数字))算余数 ...

  8. 2018.09.30 bzoj2741: 【FOTILE模拟赛】L(分块+可持久化01trie)

    传送门 数据结构经典题. 首先考虑另外一种询问方式. 已知权值val,在区间[1,n][1,n][1,n]中找一个数使得valvalval^a[i]a[i]a[i]最大. 这个可以直接01trie. ...

  9. 2018.07.31cogs2964. 数列操作η(线段树)

    传送门 线段树基本操作. 给出一个排列b,有一个初始值都为0的数组a,维护区间加1,区间统计区间∑(ai/bi)" role="presentation" style=& ...

  10. UVaLive 4597 Inspection (网络流,最小流)

    题意:给出一张有向图,每次你可以从图中的任意一点出发,经过若干条边后停止,然后问你最少走几次可以将图中的每条边都走过至少一次,并且要输出方案,这个转化为网络流的话,就相当于 求一个最小流,并且存在下界 ...