这篇文章是程序自动发表的,详情可以见
这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这篇文章是程序自动生成并发表的,详情可以见这篇文章
这是leetcode的第698题--Partition to K Equal Sum Subsets
题目 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
思路 先排好序,然后对当前剩余的最大的数,判断是否存在一组数使等于平均值。通过将两个数相加,一直归并,如果不成立,则回溯,直到成立,或者没有选择则返回False
show me the code
class Solution: def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ n=len(nums) s , res= divmod(sum(nums),k) if res!=0 :return False nums.sort() return self._util(nums,s,k) def _util(self,nums,s,n): #print(nums,s,n) if nums == [] and n==0:return True elif nums ==[] or n==0:return False if nums[-1] >s:return False elif nums[-1] ==s:return self._util(nums[:-1],s,n-1) else: if nums[-1] nums[0]>s:return False elif nums[-1] nums[0]==s:return self._util(nums[1:-1],s,n-1) else: ln = len(nums) i=1 for i in range(1,ln-1): if nums[i] nums[-1]==s: nums.remove(nums[i]) return self._util(nums[:-1],s,n-1) elif nums[i] nums[-1]>s: break for j in range(i): li =nums[0:j] nums[j 1:] li[-1] =nums[j] if self._util(li,s,n):return True else:return False

本文介绍LeetCode上第698题Partition to K Equal Sum Subsets的解决思路及代码实现。该题旨在判断是否能将一个整数数组分割成k个非空子集且各子集之和相等。文章首先概述了问题背景,随后详细阐述了解决方案,包括排序和递归搜索等关键步骤。

被折叠的 条评论
为什么被折叠?



