698. 划分为k个相等的子集

698. 划分为k个相等的子集

状态压缩dp

class Solution {
 public:
  bool canPartitionKSubsets(vector& nums, int k) {
    int n = nums.size();
    vector cursum(1 << n, 0);
    vector f(1 << n, false);
    f[0] = true;
    int sum = 0;
    for (auto i : nums) sum += i;
    if (sum % k) return false;
    int tar = sum / k;

    for (int state = 0; state < 1 << n; state++) {
      if (!f[state]) continue;

      for (int j = 0; j < n; j++) {
        if (state & (1 << j)) continue;
        int nxt = state | (1 << j);
        if (cursum[state] % tar + nums[j] <= tar) {
          cursum[nxt] = cursum[state] + nums[j];
          f[nxt] = true;
        } else
          break;
      }
    }
    return f[(1 << n) - 1];
  }
};

你可能感兴趣的:(698. 划分为k个相等的子集)