[WXM] LeetCode 698. Partition to K Equal Sum Subsets C++

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.

Approach

  1. 题目大意是问你这个数组能分分成K份和相等的数组。这道题其实是变式题,与473. Matchsticks to Square几乎是一样的,只不过它限制了K只等于4,而这里K是变动的,不过解题的思路都是一样的,因为K的数据不大,完全可以用深搜解决,我们首先要判断这个数组能否分成K份,我们开辟K大的数组p,然后我们要对数组从大到小排序,为什么要排序,我们要让K份恰好达到平均数,而不是中间某些数凑成的和,其实也主要是为了减少搜索,然后我们就深索数组从0~N,将其中的元素轮流放入p某个中,最后达到边界判断是否能分成K份,不行则回溯重新装入p某个中,剩余看代码加深理解。
  2. [WXM] 473. Matchsticks to Square
    类似的题

Code

class Solution {
public:
    bool isvalid(vector<int> &dp) {
        for (int i = 0; i < dp.size()-1; i++) {
            if (dp[i] != dp[i + 1])return false;
        }
        return true;
    }
    bool helper(vector<int>&nums,int c,int k,vector<int>&dp,int pos) {
        if (pos == nums.size())return isvalid(dp);
        for (int i = 0; i < k; i++) {
            if (dp[i] + nums[pos] <= c) {
                dp[i] += nums[pos];
                if (helper(nums, c, k, dp, pos + 1))return true;
                else dp[i] -= nums[pos];
            }
        }
        return false;
    }
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        int n = nums.size();
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if (sum%k)return false;
        int c = sum / k;
        vector<int>dp(k, 0);
        sort(nums.rbegin(), nums.rend());
        return helper(nums, c, k, dp, 0);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值