📜  leetcode 416 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:33.633000             🧑  作者: Mango

代码示例1
Using memoization
class Solution {
    public boolean canPartition(int[] nums) {
        
        Arrays.sort(nums);
        int total = 0;
        
        for(int num:nums)
        total+=num;
        
        
        if(total%2!=0)
        return false;
        
        return canPartition(nums,0,0,total, new HashMap());
        
    }
    
    public boolean canPartition(int[] nums, int index,  int sum , int total , HashMap state)
    {
        String current = index + "" + sum;
        
        if(state.containsKey(current))
            return state.get(current);
        
        if(sum*2==total)
            return true;
        
        if(sum > total || index >= nums.length)
            return false;
        
        boolean result =  canPartition(nums, index+1 , sum , total,state) ||  canPartition(nums,index+1,sum+nums[index],total,state );
        
        state.put(current, result);
        
        return result;
        
    }
    
}