[Leetcode]698.Partition to K Equal Sum Subsets

Links: LeetCode698

Given an integer array nums and a positive integer k, it is possible to find out whether the array is divided into k non-empty sets, the sum of which are equal.

Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Description: There may be divided into four subsets (5), (1,4), ( 2,3), (2,3) equal to the sum.

Related tags: depth-first search

It can be solved by depth-first search. The key point is that when we are looking for the formation of sub-arrays target, we must first consider the large number of the array, as if a small number can be composed of large numbers, first use a decimal avoid running out of the back of Tarsus, Tarsus not the composition of the target. Figured that, in fact, this question can be solved by conventional methods.

Code is as follows:

python:

class Solution:
    def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
        sum_ = sum(nums)
        if sum_%k or max(nums)>sum_//k:return False
        nums.sort(reverse=True)
        return self.dfs(nums,sum_//k,sum_//k)

    def dfs(self,nums,cur,target):
        if not nums and not cur:return True
        if not cur:
            cur = target
        for i in range(len(nums)):
            if cur >= nums[i]:
                rest = nums[:i]+nums[i+1:]
                if self.dfs(rest,cur-nums[i],target):
                    return True
        return False

C++:

class Solution {
public:
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        int sum_ = accumulate(nums.begin(),nums.end(),0);
        if(sum_%k!=0 || *max_element(nums.begin(),nums.end())>sum_/k) return false;
        sort(nums.begin(),nums.end(),greater<int>());
        int target = sum_/k;
        return dfs(nums,target,target);
    }

    bool dfs(vector<int> &nums,int cur,int target){
        if(nums.empty() && cur==0){return true;}
        if(cur==0) {
            cur=target;
        }
        for(int i=0;i<nums.size();++i){
            if(cur>=nums[i]){
                vector<int> rest;
                for(int j=0;j<nums.size();++j){
                    if(j!=i){rest.push_back(nums[j]);}
                }
                if(dfs(rest,cur-nums[i],target)){return true;}
            }
        }
        return false;
    }
};

Guess you like

Origin www.cnblogs.com/hellojamest/p/12285244.html