leetcode 698. Partition to K Equal Sum Subsets

本文探讨了如何将一组整数等分为k个子集,使每个子集的和相等的问题。通过递归搜索和回溯算法实现解决方案,并提供了一个具体的例子说明其可行性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


    class Solution {
    public:
        bool canPartitionKSubsets(vector<int>& nums, int k) 
        {
            //先要知道sum是多少
            sum = 0;
            for (auto it : nums)
                sum += it;
            if (sum % k != 0) return false;
            sum = sum / k;
            sort(nums.begin(), nums.end(), greater<int>());
            for (int i = 0; i < k; i++)
                group.push_back(0);
            return helper(nums, 0, group, sum);
        }
        
        bool helper(vector<int>& nums, 
                    int i,   //当前需要安排第i个
                    vector<int> group,
                    int all) //每一组的和
        {
            if (i == nums.size()) return true;
            for (int j = 0; j < group.size(); j++)
            {
                if (group[j] + nums[i] <= all) //可以往里面放
                {
                    group[j] += nums[i]; 
                    if (helper(nums, i + 1, group, all)) return true;
                    group[j] -= nums[i];
                }
            }
            return false;
        }
        
    private:
        int sum;
        vector<int> group;
    };




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值