24
24
public class _46 {
25
25
26
26
public static class Solution1 {
27
- //this solution has a backtracking function that its return type is not void
28
27
public List <List <Integer >> permute (int [] nums ) {
29
28
List <List <Integer >> result = new ArrayList ();
30
29
result .add (new ArrayList <>());
@@ -37,7 +36,7 @@ private List<List<Integer>> backtracking(List<List<Integer>> result, int[] nums,
37
36
}
38
37
List <List <Integer >> newResult = new ArrayList ();
39
38
for (List <Integer > eachList : result ) {
40
- for (int i = 0 ; i <= eachList .size (); i ++) {
39
+ for (int i = 0 ; i <= eachList .size (); i ++) {//attn: i starts from 0
41
40
List <Integer > newList = new ArrayList (eachList );
42
41
newList .add (i , nums [pos ]);
43
42
newResult .add (newList );
@@ -48,33 +47,4 @@ private List<List<Integer>> backtracking(List<List<Integer>> result, int[] nums,
48
47
}
49
48
}
50
49
51
- public static class Solution2 {
52
- public List <List <Integer >> permute (int [] nums ) {
53
- List <List <Integer >> result = new ArrayList ();
54
- result .add (new ArrayList <>());
55
- recursive (result , nums , 0 );
56
- return result ;
57
- }
58
-
59
- private void recursive (List <List <Integer >> result , int [] nums , int pos ) {
60
- if (pos == nums .length ) {
61
- return ;
62
- }
63
- List <List <Integer >> newResult = new ArrayList ();
64
- for (List <Integer > eachList : result ) {
65
- for (int i = 0 ; i <= eachList .size (); i ++) {
66
- List <Integer > newList = new ArrayList (eachList );
67
- newList .add (i , nums [pos ]);
68
- newResult .add (newList );
69
- }
70
- }
71
- /**You'll have to use the two lines, instead of this line: result = newResult; otherwise, it won't work!!!*/
72
- result .clear ();
73
- result .addAll (newResult );
74
-
75
- //then recursion
76
- recursive (result , nums , pos + 1 );
77
- }
78
- }
79
-
80
50
}
0 commit comments