|
| 1 | +//The idea is to have two conditions: One in which we will take the element into consideration, Second in which we won't take the element into consideration. |
| 2 | +//This video was good for code explanation. https://www.youtube.com/watch?v=6BPurabdAl4&t=508s&ab_channel=Fraz |
| 3 | +classSolution { |
| 4 | +publicList<List<Integer>>subsets(int[]nums) { |
| 5 | +List<List<Integer>>ans =newArrayList<>(); |
| 6 | +List<Integer>list =newArrayList<>(); |
| 7 | +helper(ans,0,nums,list); |
| 8 | +returnans; |
| 9 | + } |
| 10 | + |
| 11 | +publicvoidhelper(List<List<Integer>>ans,intstart,int[]nums,List<Integer>list) { |
| 12 | +if (start>=nums.length) { |
| 13 | +ans.add(newArrayList<>(list));//In java, we will have to add like this otherwise it'll give null as it'll just have the reference instead of actual values. |
| 14 | + }else { |
| 15 | +//add the element and start the recursive call |
| 16 | +list.add(nums[start]); |
| 17 | +helper(ans,start+1,nums,list); |
| 18 | +//remove the element and do the backtracking call. |
| 19 | +list.remove(list.size()-1); |
| 20 | +helper(ans,start+1,nums,list); |
| 21 | + } |
| 22 | + } |
| 23 | +} |