daily progress
- Pruning: Avoid some unnecessary traversal processes by judging.
- Feasibility pruning: backtrack when the solution is not feasible.
- Optimal pruning: backtracking when the solution of the scheme cannot be better than the current optimal solution.
topic
Given an array of integers nums
and a positive integer k
, find whether it is possible to partition the array into k
non-empty subsets whose sums are all equal.
- Example 1:
- Enter:
nums = [4, 3, 2, 3, 5, 2, 1]
,k = 4
- output:
True
- Explanation: It is possible to divide it into 4 subsets (5), (1,4), (2,3), (2,3) equal to the sum.
- Enter:
- Example 2:
- input:
nums = [1,2,3,4]
,k = 3
- output:
false
- input:
- hint:
1 <= k <= len(nums) <= 16
0 < nums[i] < 10000
- The frequency of each element is in the range [1,4]
Source: LeetCode
Link: https://leetcode.cn/problems/partition-to-k-equal-sum-subsets
The copyright belongs to Leetcode Network. This article is for personal study only, non-commercial use.
answer
Adopt the idea of depth-first traversal and pruning , and use a greedy strategy.
class Solution {
int[] solu_nums;
int solu_k, len, key;
public boolean canPartitionKSubsets(int[] nums, int k) {
solu_nums = nums;
solu_k = k;
len = nums.length;
int sum = 0;
for (int num : nums){
sum += num;
}
if (sum % k != 0)
return false;
key = sum / k;
Arrays.sort(solu_nums);
boolean[] visited = new boolean[len];
Arrays.fill(visited, false);
boolean ans = dfs(len-1, 0, 0, visited);
return ans;
}
public boolean dfs(int idx, int cal, int times, boolean visited[]){
if (times == solu_k)
return true;
if (cal == key)
return dfs(len-1, 0, times+1, visited);
for (int i = idx; i >= 0; i--){
if (visited[i] == true || cal + solu_nums[i] > key)
continue;
visited[i] = true;
boolean ans = dfs(idx-1, cal+solu_nums[i], times, visited);
if (ans)
return true;
else
visited[i] = false;
if (cal == 0)
return false;
}
return false;
}
}
The solution of this question refers to the thought of this big guy
Link: https://leetcode.cn/problems/partition-to-k-equal-sum-subsets/solution/by-ac_oier-mryw/