fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public List<List<Integer>> subsetsWithNew(int[] nums) {
  11. List<List<Integer>> res = new ArrayList<>();
  12. if(nums==null || nums.length==0) return res;
  13. dfsWithNew(res, new ArrayList<>(), 0, nums);
  14. return res;
  15. }
  16.  
  17. private void dfsWithNew(List<List<Integer>> res, List<Integer> list, int pos, int[] nums) {
  18. res.add(new ArrayList<Integer>(list));
  19. if(pos==nums.length+1) return;
  20. for(int i=pos; i<nums.length; i++) {
  21. list.add(nums[i]);
  22. dfsWithNew(res, list, i+1, nums);
  23. list.remove(list.size()-1);
  24. }
  25. }
  26.  
  27. public List<List<Integer>> subsetsWithoutNew(int[] nums) {
  28. List<List<Integer>> res = new ArrayList<>();
  29. if(nums==null || nums.length==0) return res;
  30. dfsWithoutNew(res, new ArrayList<>(), 0, nums);
  31. return res;
  32. }
  33.  
  34. private void dfsWithoutNew(List<List<Integer>> res, List<Integer> list, int pos, int[] nums) {
  35. res.add(list);
  36. if(pos==nums.length+1) return;
  37. for(int i=pos; i<nums.length; i++) {
  38. list.add(nums[i]);
  39. dfsWithoutNew(res, list, i+1, nums);
  40. list.remove(list.size()-1);
  41. }
  42. }
  43.  
  44. public static void main (String[] args) throws java.lang.Exception
  45. {
  46. Ideone app = new Ideone();
  47. int[] nums = { 5, 2 };
  48.  
  49. System.out.println("*** With new ***");
  50. List<List<Integer>> subsets = app.subsetsWithNew(nums);
  51. subsets.forEach(System.out::println);
  52.  
  53. System.out.println("*** Without new ***");
  54. subsets = app.subsetsWithoutNew(nums);
  55. subsets.forEach(System.out::println);
  56. }
  57. }
Success #stdin #stdout 0.16s 33268KB
stdin
Standard input is empty
stdout
*** With new ***
[]
[5]
[5, 2]
[2]
*** Without new ***
[]
[]
[]
[]