惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Cloudflare Blog
L
LangChain Blog
WordPress大学
WordPress大学
V
V2EX
M
MIT News - Artificial intelligence
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
Docker
Recent Announcements
Recent Announcements
GbyAI
GbyAI
博客园 - 叶小钗
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
T
The Blog of Author Tim Ferriss
人人都是产品经理
人人都是产品经理
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
雷峰网
雷峰网
The GitHub Blog
The GitHub Blog

博客园 - katago

【最大子矩形】极大化思想 MobaXterm-Keygen The "vmwgfx unsupported hypervisor" error in VirtualBox with Ubuntu codex 安装必备环境 chatgpt提示词 通过VScode的远程连接 WSL,配置Linux平台python开发环境 扫地机器人基本设计方案 wsl2 安装 SRS + FFmpeg 直播机 拉流推给本机 SRS 的 RTMP P1171 售货员的难题 dfs 状态压缩 + 记忆化搜索 P1171 售货员的难题 for循环状压dp写法 LeetCode 473. 火柴拼正方形 vscode LeetCode插件安装 LeetCode 464. 我能赢吗 P1825 [USACO11OPEN] Corn Maze S 如何找代码bug 八中 搜索作业 线性筛素数计数 atcoder dp基础 八中上机课练习题单 整除分块
leetcode [698] 划分为k个相等的子集
katago · 2026-01-07 · via 博客园 - katago

https://leetcode.cn/problems/partition-to-k-equal-sum-subsets/description/

拼火柴一样, 改为k个集合

/*
 * @lc app=leetcode.cn id=698 lang=cpp
 *
 * [698] 划分为k个相等的子集
 */

// @lc code=start
class Solution {
public:
    int dp[1 << 16];
    int n;
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        n = nums.size();
        int sum = 0;
        for (int num : nums) sum += num;
        if (sum % k != 0) return false;
        int target = sum / k;
        sort(nums.begin(), nums.end(), greater<int>());
        memset(dp, -1, sizeof(dp));
        return dfs(0, 0, k, target, nums);
    }
    bool dfs(int status, int cur, int rest, int target, vector<int>& nums) {
        if (rest == 0) return true;
        if (dp[status] != -1) return dp[status];
        for (int i = 0; i < n; i++) {
            if ((status >> i) & 1) continue;
            if (cur + nums[i] > target) continue;
            int nstatus = status | (1 << i);
            int nrest = rest;
            int ncur = cur + nums[i];
            if( ncur == target) {
                nrest--;
                ncur = 0;
            }
            if (dfs(nstatus, ncur, nrest, target, nums)) {
                dp[status] = 1;
                return true;
            }
        }
        dp[status] = 0;
        return false;
    }
};