698. Partition to K Equal Sum Su

2018-07-26  本文已影响0人  becauseyou_90cd

https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/

解题思路:

  1. 用深搜方法

代码:
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;
}

}

上一篇下一篇

猜你喜欢

热点阅读