美文网首页
698. Partition to K Equal Sum Su

698. Partition to K Equal Sum Su

作者: becauseyou_90cd | 来源:发表于2018-07-26 05:52 被阅读0次

    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;
    }
    

    }

    相关文章

      网友评论

          本文标题:698. Partition to K Equal Sum Su

          本文链接:https://www.haomeiwen.com/subject/slrvmftx.html