zoukankan      html  css  js  c++  java
  • 698. Partition to K Equal Sum Subsets

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

    Use DFS. We need to choose k group of numbers (each group sum to s). The state is 1) how many groups left, 2) current sum in current group, 3) visisted for each number.

    If given state1 (k, cur, visited), we choose a number (make sure this number is not visited, this number + cur <= s), then the state is updated to (k, cur+current number, visited). Then we need to pick another number in new state. That's the sub-problem.

    Optimization: sort nums in desc order, and always pick the first (biggest) number for the first group.

    class Solution {
    public:
        bool canPartitionKSubsets(vector<int>& nums, int k) {
            int s = 0;
            for (auto i : nums)
                s += i;
            if (s % k != 0) return false;
            s = s / k;
            
            // sort in desc order
            sort(nums.begin(), nums.end());
            reverse(nums.begin(), nums.end());
            
            // first set contains the biggest number
            vector<bool> visited(nums.size(), false);
            visited[0] = true;
            
            return dfs(nums, visited, s, nums[0], k);
        }
        bool dfs(vector<int>& nums, vector<bool>& visited, int s, int cur, int k) {
            if (cur == s) {
                k--;
                cur = 0;
                if (k == 0) return true;
            }
            for (int i = 1; i < nums.size(); i++) {
                if (!visited[i] && nums[i] + cur <= s) {
                    visited[i] = true;
                    bool res = dfs(nums, visited, s, cur + nums[i], k);
                    visited[i] = false;
                    if (res)    return res;
                }
            }
            return false;
        }
    };
  • 相关阅读:
    修改Anaconda中Jupyter Notebook默认工作路径
    npm卸载和安装淘宝镜像原
    hash和history两种模式的区别
    威胁建模之WEB应用自动化截图
    Ubuntu系统清理
    Ubuntu环境的docker实践——ONOS
    BUUCTF-crypto:信息化时代的步伐
    BUUCTF-crypto:四面八方
    BUUCTF-crypto:[HDCTF2019]basic rsa
    BUUCTF-crypto:rsarsa
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8997097.html
Copyright © 2011-2022 走看看