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
- Leetcode-416. Partition Equal Subset Sum
- LeetCode—416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum
- 【leetcode】416. Partition Equal Subset Sum
- 【LeetCode】416. Partition Equal Subset Sum
- 【LeetCode】416. Partition Equal Subset Sum
- LeetCode 416. Partition Equal Subset Sum
- 【LeetCode】416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum[medium]
- [LeetCode]416. Partition Equal Subset Sum
- 【LeetCode】 416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum
- Leetcode-416. Partition Equal Subset Sum
- LeetCode 416. Partition Equal Subset Sum
- [leetcode]416. Partition Equal Subset Sum
- LeetCode 416. Partition Equal Subset Sum
- Leetcode Algorithm 416. Partition Equal Subset Sum
- LeetCode 416. Partition Equal Subset Sum
- 让sql语句不排序,按照in语句的顺序返回结果
- 51nod 1268 和为k的组合
- [LeetCode]344. Reverse String
- POJ 2749 || HDU 1815 Building roads 2-sat
- 删除单链表中第k个节点
- Leetcode-416. Partition Equal Subset Sum
- Android架构蓝图------MVP
- 旅游攻略
- 什么叫过滤器呢?
- 【bzoj 3172】【codevs 2542】[Tjoi2013]单词(AC自动机)
- linux菜鸟入门之压缩以及归档
- laravel开发环境homestead搭建
- CSS 入门 笔记
- 阿里云配置tomcat