698. Partition to K Equal Sum Subsets

Medium
L家的tag题,之前contest好像是做过但没有做出来当时,这道题看了答案然后写出了一个及其奇怪的bug.

class Solution {
    public boolean canPartitionKSubsets(int[] nums, int k) {
        int sum = 0;
        for (int num : nums){
            sum += num;
        }
        if (sum % k != 0){
            return false;
        }
        int subSum = sum / k;
        Arrays.sort(nums);
        if (nums[nums.length - 1] > subSum){
            return false;
        }
        int beginIndex = nums.length - 1;
        while (beginIndex >= 0 && nums[beginIndex] == subSum){
            beginIndex--;
            k--;
        }
        return canPartition(new int[k], nums, subSum, beginIndex);
    }

    private boolean canPartition(int[] subsets, int[] nums, int target, int index){
        if (index < 0){
            return true;
        }
        int curtNum = nums[index];
        for (int i = 0; i < subsets.length; i++){
            if (subsets[i] + curtNum <= target){
                subsets[i] += curtNum;
                if (canPartition(subsets, nums, target, index - 1)){
                    return true;
                }
                subsets[i] -= curtNum;
            }
        }
        return false;
    }
}

    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/06553edf0b33
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞