【leetcode】416. Partition Equal Subset Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86559985

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:

  1. Each of the array element will not exceed 100.
  2. The array size will not exceed 200.

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

代码实现如下:

class Solution {
    public boolean canPartition(int[] nums) {
        int sum = 0;
        for(int i=0;i<nums.length;i++){
            sum += nums[i];
        }
        if((sum & 1) == 1)
            return false;
        int target = sum/2;
        Arrays.sort(nums);
        int row = nums.length - 1;
        if(nums[row]>target){
            return false;
        }
        if(nums[row]==target){
            row--;
            return search(new int[1],nums,row,target);
        } else {
            return search(new int[2],nums,row,target);
        }
        
    }
    
    public boolean search(int[] groups,int[] nums,int row,int target){
        if(row<0){
            return true;
        }
        int v = nums[row--];
        for(int i=0;i<groups.length;i++){
            if(groups[i] + v <= target){
                groups[i] += v;
                if(search(groups,nums,row,target))
                    return true;
                groups[i] -= v;//如果到达这里,说明上面的方案无法达到目标,需重置
            }
            if(groups[i] == 0){
                break;//有方案不可行
            }
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/86559985