【LeetCode】698.Partition to K Equal Sum Subsets(Medium)解题报告

来源:互联网 发布:四十而知天命 编辑:程序博客网 时间:2024/05/17 02:03

【LeetCode】698.Partition to K Equal Sum Subsets(Medium)解题报告

题目地址:https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/
题目描述:

  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 = 4Output: TrueExplanation: 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.

  第一个代码使自己写的没有a过,但是自己没查出来错误。后面答案小傅的a了。

Solution1:

class Solution {    public boolean canPartitionKSubsets(int[] nums, int k) {        Arrays.sort(nums);        int count = 0;        int len = nums.length;        for(int i=0;i<len;i++){            count+=nums[i];        }        int h = count%k==0?count/k:0;        int newLen=0;        for(int i=len-1;;i--){            if(nums[i]==h){                newLen = len-1;            }else if(nums[len-1]>h){                return false;            }else{                break;            }        }        for(int i=newLen-1,t=0; i>0 && t<i ; i--,t++){            if(nums[i]+nums[t]==h){                continue;            }else{                return false;            }        }        return true;    }}[5,2,5,5,5,5,5,5,5,5,5,5,5,5,5,3]15显示错误。

Solution2:

class Solution {    public boolean canPartitionKSubsets(int[] nums, int k) {        int sum = sum(nums);        if(sum%k!=0){            return false;        }        int subSum = sum/k;        Arrays.sort(nums);        int beginIndex = nums.length - 1;        if(nums[beginIndex]>subSum){            return false;        }        while(beginIndex>=0 && nums[beginIndex]==subSum ){            beginIndex--;            k--;        }        return partition(new int[k], nums,beginIndex,subSum);    }    public boolean partition(int[] subsets, int[] nums ,int index, int target ){        if(index<0){            return true;        }        int selected = nums[index];        for(int i=0 ; i<subsets.length ; i++){            if(subsets[i]+selected<=target){                subsets[i]+=selected;                if(partition(subsets,nums,index-1,target)){                    return true;                }                subsets[i]-=selected;            }        }        return false;    }    public int sum(int[] nums){        int res=0;        for(int i=0 ; i<nums.length ; i++){            res+=nums[i];        }        return res;    }}

Date:2017年11月22日

原创粉丝点击