• 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;
        }
    };
  • 相关阅读:
    设计模式 策略模式
    Java 集合 LinkedList的ListIterator
    Java 集合 JDK1.7的LinkedList
    Java 集合 集合与数组之间的转换
    Java Object 对象拷贝答疑
    Java Object 对象拷贝
    Java 集合 fail-fast机制 [ 转载 ]
    .net知识点汇总
    Javascript知识点汇总-初级篇
    Javascript实用技巧
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8997097.html
Copyright © 2020-2023  润新知