LC 416. Partition Equal Subset Sum

topic

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.

Answers

. 1  class Solution {
 2  public :
 . 3      BOOL canPartition (Vector < int > & the nums) {
 . 4          int SUM = the accumulate (nums.begin (), nums.end (), 0 ); // first summing array 
. 5          IF ( & SUM . 1 ) { // if the array is odd, it does not hold, because, for example:. 3. 5 + 2 = 
. 6              return  to false ;
 . 7          }
 . 8          int Half = SUM / 2 ;
 . 9          STD :: Sort (nums.begin (), the nums .end (), Greater STD :: < int > ()); //Must be added, otherwise limit exceeded Number Time 
10          return foo (the nums, half, 0 ); // will be half as input 
. 11      }
 12 is  
13 is      BOOL foo (Vector < int > the nums &, int half, int index) {
 14          for ( int index = I; I <nums.size (); I ++) { // iterate for every number 
15              int H = half - the nums [I]; // to deduct half 
16              IF (H < 0 ) return  to false ; 
 . 17              IF (H == 0 )return  to true ;
 18 is              // If the above conditions are not satisfied, described nums [i] can not satisfy the condition, then the need to continue looking for a number, 
20 // i.e. index = i + 1. That meet true, it does not meet the return to the top, a number in this layer are looking for.
. 19 IF (foo (the nums, H, I + . 1 ) == to true ) return to true ; 20 is } 21 is return to false ; 22 is } 23 is };

 

Guess you like

Origin www.cnblogs.com/kykai/p/11568399.html