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;
    }
};
原文地址:https://www.cnblogs.com/JTechRoad/p/8997097.html