Leetcode-416. Partition Equal Subset Sum

来源:互联网 发布:窗口编程 编辑:程序博客网 时间:2024/05/01 11:08

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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: trueExplanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]Output: falseExplanation: The array cannot be partitioned into equal sum subsets.
一个笨办法就是用O(n^2)的复杂度来看能否分成两个相等的setYour runtime beats 3.72% of java submissions.

public class Solution {    public boolean canPartition(int[] nums) {        Arrays.sort(nums);        if( nums.length == 1) return false;        int sum = 0;        for(int item : nums) sum += item;        if(sum % 2 != 0) return false;        boolean flag = false;        int mid = sum/2;        List<Integer> results = new ArrayList<Integer>();        Map<Integer,Integer> map = new HashMap<Integer, Integer>();        for(int num : nums){            if(results.size() == 0) {results.add(0, num);map.put(num,1);}            else{                results.add(0,num);                int n = results.size();                for(int i = 1; i < n ; i ++){                    if( results.get(i) == mid || results.get(i) + num == mid){flag = true; break;}                    else{                        if(!map.containsKey(results.get(i) + num)){map.put(results.get(i) + num,1);results.add(results.get(i) + num);}                    }                }            }        }        return flag;    }}

刚刚那个想法肯定不好,另外这个也是dp问题,但是我一开始dp保存的值没想清楚,dp应该保存的的是第i个物品能否保证和为j。时间复杂度O(nm)m为nums中所有元素和sum差的平均值。Your runtime beats 37.26% of java submissions.

public class Solution {    public boolean canPartition(int[] nums) {        int sum = 0;        for(int item : nums){            sum += item;        }        boolean flag = sum % 2 == 0;                if(flag){            int v = sum / 2;            int count = 0;            boolean [] dp = new boolean[v + 1];            dp[0] = true;            for(int i = 0; i < nums.length; i ++){                for(int j = v; j >= nums[i]; j --){                    dp[j] = dp[j] || dp[j - nums[i]];                }            }            flag = dp[v];        }                return flag;    }}




0 0
原创粉丝点击