|
| 1 | +packagemedium; |
| 2 | +importjava.util.ArrayList; |
| 3 | +importjava.util.List; |
| 4 | + |
| 5 | +publicclassPermutations { |
| 6 | +staticclassAccepted_solution { |
| 7 | +//this solution has a recursive function that has a return type |
| 8 | +publicstaticList<List<Integer>>permute(int[]nums) { |
| 9 | +List<List<Integer>>result =newArrayList(); |
| 10 | +result.add(newArrayList<>()); |
| 11 | +returnrecursive(result,nums,0); |
| 12 | + } |
| 13 | + |
| 14 | +privatestaticList<List<Integer>>recursive(List<List<Integer>>result,int[]nums, |
| 15 | +intpos) { |
| 16 | +if (pos ==nums.length) |
| 17 | +returnresult; |
| 18 | +List<List<Integer>>newResult =newArrayList(); |
| 19 | +for (List<Integer>eachList :result) { |
| 20 | +for (inti =0;i <=eachList.size();i++) { |
| 21 | +List<Integer>newList =newArrayList(eachList); |
| 22 | +newList.add(i,nums[pos]); |
| 23 | +newResult.add(newList); |
| 24 | + } |
| 25 | + } |
| 26 | +result =newResult; |
| 27 | +returnrecursive(result,nums,pos +1); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | +staticclassAccepted_solution_with_void_type { |
| 32 | +publicstaticList<List<Integer>>permute(int[]nums) { |
| 33 | +List<List<Integer>>result =newArrayList(); |
| 34 | +result.add(newArrayList<>()); |
| 35 | +recursive(result,nums,0); |
| 36 | +returnresult; |
| 37 | + } |
| 38 | + |
| 39 | +privatestaticvoidrecursive(List<List<Integer>>result,int[]nums,intpos) { |
| 40 | +if(pos ==nums.length)return; |
| 41 | +List<List<Integer>>newResult =newArrayList(); |
| 42 | +for(List<Integer>eachList :result){ |
| 43 | +for(inti =0;i <=eachList.size();i++){ |
| 44 | +List<Integer>newList =newArrayList(eachList); |
| 45 | +newList.add(i,nums[pos]); |
| 46 | +newResult.add(newList); |
| 47 | + } |
| 48 | + } |
| 49 | +/**You'll have to use the two lines, instead of this line: result = newResult; otherwise, it won't work!!! Fuck!*/ |
| 50 | +result.clear(); |
| 51 | +result.addAll(newResult); |
| 52 | + |
| 53 | +//then recursion |
| 54 | +recursive(result,nums,pos+1); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | +publicstaticvoidmain(String...args){ |
| 59 | +int[]nums =newint[]{1,2,2}; |
| 60 | + } |
| 61 | + |
| 62 | +} |