LWC 54:698. Partition to K Equal Sum Subsets

来源:互联网 发布:中国移动数据流量卡 编辑:程序博客网 时间:2024/06/06 15:41

LWC 54:698. Partition to K Equal Sum Subsets

传送门:698. Partition to K Equal Sum Subsets

Problem:

Given an array of integers nums and a positive integer k, find whether it’s possible to divide this array into k non-empty subsets whose sums are all equal.

Example 1:

Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It’s possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Note:

  • 1 <= k <= len(nums) <= 16.
  • 0 < nums[i] < 10000.

思路:
观察 k 和 n 发现均很小,所以实际上是暴力dfs算法,先预处理,如果sum / k 有余数,则不能分割。接着nums中的每个元素对应k个状态,所有有nk中情况,dfs用到了剪枝,排序贪心尽早把不合法的解从递归树中删除。

代码如下:

    public boolean canPartitionKSubsets(int[] nums, int k) {        int sum = 0;        int max = 0;        int n = nums.length;        for (int i = 0; i < n; ++i) {            sum += nums[i];            max = Math.max(max, nums[i]);        }        if (sum % k != 0) return false;        tar = sum / k;        if (max > tar) return false;        Arrays.sort(nums);        return go(nums, n - 1, k, new int[k]);    }    int tar = 0;    boolean go(int[] nums, int pos, int k, int[] sums) {        if (pos == -1) {            boolean check = true;            for (int i = 0; i < k; ++i) {                if (sums[i] != tar) check = false;            }            return check;        }        for (int i = 0; i < k; ++i) {            sums[i] += nums[pos];            if (sums[i] <= tar && go(nums, pos - 1, k, sums)) {                return true;            }            sums[i] -= nums[pos];        }        return false;    }
原创粉丝点击