https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/
解题思路:
- 用深搜方法
代码:
class Solution {
public boolean canPartitionKSubsets(int[] nums, int k) {
int sum = 0;
for (int num : nums){
sum += num;
}
if(sum % k != 0) return false;
sum /= k;
int[] visited = new int[nums.length];
return helper(nums, sum, visited, 0, k, 0, 0);
}
public boolean helper(int[] nums, int target, int[] visited, int startIndex, int k, int curSum, int curNum){
if(k == 1) return true;
if(curSum == target && curNum > 0) return helper(nums, target, visited, 0, k-1, 0, 0);
for(int i = startIndex; i < nums.length; i++){
if(visited[i]== 0){
visited[i] = 1;
if(helper(nums, target, visited, i+1, k, curSum + nums[i], curNum++))return true;
visited[i] = 0;
}}
return false;
}
}
网友评论