How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

前端 未结 22 981
一生所求
一生所求 2020-12-02 11:20

How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

22条回答
  •  春和景丽
    2020-12-02 11:59

    very simple solution with recursion

    public boolean splitArray(int[] nums){
                return arrCheck(0, nums, 0);
            }
    
    public boolean arrCheck(int start, int[] nums, int tot){
                if(start >= nums.length) return tot == 0;
                if(arrCheck(start+1, nums, tot+nums[start])) return true;
                if(arrCheck(start+1, nums, tot-nums[start])) return true;
                return false;
            }
    

提交回复
热议问题