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.題目的意思是輸入一個非空的、只含正整數的數組nums,要求咱們判斷,數組nums可否被分紅兩個子數組,知足兩個子數組的和相等。數組
例1:
輸入: [1, 5, 11, 5]
輸出: true
解釋: 輸入數組能夠被分爲[1, 5, 5]和[11].
例2:
輸入: [1, 2, 3, 5]
輸出: false
解釋: 數組沒法被拆分紅兩個和相等的子數組.code
public boolean canPartition(int[] nums) { int sum = 0; for(int num : nums){ sum += num; } if(sum % 2 != 0)return false; sum /= 2; boolean[] res = new boolean[sum+1]; int length = nums.length; res[0] = true; for(int i=1;i<=length;i++){ for(int j=sum;j>=nums[i-1];j--){ res[j] = res[j-nums[i-1]] || res[j]; } } return res[sum]; }