Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. public class Solution {
  2. // public boolean canPartition(int[] nums) {
  3. // int s = 0;
  4. // for(int n:nums){
  5. // s += n;
  6. // }
  7. // if(s%2!=0) return false;
  8. // s = s/2;
  9. // boolean[] d = new boolean[s+1];
  10. // d[0] = true;
  11. // for(int i=0;i<nums.length;i++){
  12. // for(int j=s;j>=0;j--){
  13. // if(((j-nums[i])>=0)&&d[j-nums[i]]){
  14. // d[j] = true;
  15. // }
  16. // }
  17. // }
  18. // return d[s];
  19. // }
  20. public boolean canPartition(int[] nums) {
  21. int sum=0;
  22. for(int n : nums)
  23. sum += n;
  24.  
  25. if(sum%2==1)
  26. return false;
  27.  
  28. return helper(nums, 0, 0, sum/2, new HashSet<Integer>());
  29. }
  30.  
  31. private boolean helper(int[] nums, int index, int cur, int target, Set<Integer> set){
  32. if(set.contains(cur))
  33. return false;
  34. if(cur==target)
  35. return true;
  36. if(cur>target)
  37. return false;
  38.  
  39. for(int i=index; i<nums.length; i++)
  40. if( helper(nums, i+1, cur+nums[i], target, set) )
  41. return true;
  42.  
  43. set.add(cur);
  44. return false;
  45. }
  46.  
  47.  
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement