11package LeetcodeQuestions ;
22
33import java .util .ArrayList ;
4+ import java .util .Arrays ;
45import java .util .List ;
56
67// https://leetcode.com/problems/permutations/
78
8-
9+
910// https://github.com/shashankch/DataStructures-Algo-Java/blob/master/src/PrepStringPermuteBacktrack.java
1011
1112public class permutations {
@@ -27,7 +28,7 @@ public static void permute(int[] nums, int i, List<List<Integer>> list) {
2728
2829 }
2930
30- public static void swap (int [] nums , int i , int j ) {
31+ public static void swap (int [] nums , int i , int j ) {
3132 int temp = nums [i ];
3233 nums [i ] = nums [j ];
3334 nums [j ] = temp ;
@@ -42,15 +43,58 @@ public static List<List<Integer>> helper(int[] nums) {
4243
4344
4445 }
45-
46+
47+
48+ // Method 2-------------->
49+
50+ public static void backtrack (List <List <Integer >> list , List <Integer > tempList , int [] nums ) {
51+ if (tempList .size () == nums .length ) {
52+ list .add (new ArrayList <>(tempList ));
53+ } else {
54+ for (int i = 0 ; i < nums .length ; i ++) {
55+ if (tempList .contains (nums [i ]))
56+ continue ; // element already exists, skip
57+ tempList .add (nums [i ]);
58+ backtrack (list , tempList , nums );
59+ tempList .remove (tempList .size () - 1 );
60+ }
61+ }
62+ }
63+
64+ // Method 2 with duplicate values...
65+ public static void backtrack2 (List <List <Integer >> list , List <Integer > tempList , int [] nums ,
66+ boolean [] used ) {
67+ if (tempList .size () == nums .length ) {
68+ list .add (new ArrayList <>(tempList ));
69+ } else {
70+ for (int i = 0 ; i < nums .length ; i ++) {
71+ if (used [i ] || i > 0 && nums [i ] == nums [i - 1 ] && !used [i - 1 ])
72+ continue ;
73+ used [i ] = true ;
74+ tempList .add (nums [i ]);
75+ backtrack2 (list , tempList , nums , used );
76+ used [i ] = false ;
77+ tempList .remove (tempList .size () - 1 );
78+ }
79+ }
80+ }
81+
82+
83+ public List <List <Integer >> helper2 (int [] nums ) {
84+ List <List <Integer >> list = new ArrayList <>();
85+ Arrays .sort (nums ); // sorting needed in duplicate values case
86+ backtrack2 (list , new ArrayList <>(), nums , new boolean [nums .length ]);
87+ return list ;
88+ }
89+
4690
4791 public static void main (String [] args ) {
48-
92+
4993 int arr [] = {1 , 2 , 3 };
5094 for (List <Integer > li : helper (arr )) {
5195
5296 System .out .println (li );
53-
97+
5498 }
5599
56100 }
0 commit comments