416. Partition Equal Subset Sum

416. Partition Equal Subset Sum

  • 題目描述: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.
  • 題目大意:給定一個數組,問數組能否分爲兩個相同的部分

  • 思路:dp,dp[i]表示數字i是否是原數組中任意個子集合的和,只需找到dp[target]是否爲真,target等於數組中所有元素和除以2,如果數組中所有元素和不能整除2則返回false。

    狀態轉移方程:dp[j] = dp[j] || dp[j - nums[i]] (nums[i] <= j <= target)

  • 代碼:

    package DP;
    
    /**
    * @author OovEver
    * 2018/1/6 16:43
    */
    public class LeetCode416 {
      public boolean canPartition(int[] nums) {
          if (nums == null || nums.length == 0) {
              return true;
          }
          int sum = 0;
          for (int i=0;i<nums.length;i++) {
              sum += nums[i];
          }
          if (sum % 2 != 0) {
              return false;
          }
          int target = sum / 2;
          boolean[] dp = new boolean[target + 1];
          dp[0] = true;
          for(int i=0;i<nums.length;i++) {
              for(int j=target;j>=nums[i];j--) {
                  dp[j] = dp[j] || dp[j - nums[i]];
              }
          }
          return dp[target];
      }
    }
    
發佈了207 篇原創文章 · 獲贊 69 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章