Leetcode-416. Partition Equal Subset Sum

来源:互联网 发布:道路工程预算软件 编辑:程序博客网 时间:2024/04/30 17:10

前言:正好碰见Leetcode有一次在线笔试,测试一下,还是挺开心的,全做出来了Rank:98/869。如有错误欢迎指正。博主首发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:
Both the array size and each of the array element will not exceed 100.

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.
这个题目有点意思,我一开始想错了,结果就是导致我这个题目错了4次,大大影响了我的排名。最终的思路是先排序,然后用List来保存所有可能的结果,用Hash保证每一个结果存储一次。

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;    }}





0 0