Skip to content

Commit 86b5e2a

Browse files
committed
add remove method to reach the otherwise way
1 parent 078411a commit 86b5e2a

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

code/LeetCode/src/backtracking/FactorCombinations.java

+17-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ public List<List<Integer>> getFactors(int n) {
1818
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
1919
// DFS
2020
//dfs(resultList, new ArrayList<Integer>(), n, 2);
21-
dfs1(resultList, new ArrayList<Integer>(), n, 2);
21+
//dfs1(resultList, new ArrayList<Integer>(), n, 2);
22+
dfs2(resultList, new ArrayList<Integer>(), n, 2);
2223

2324
return resultList;
2425
}
@@ -52,7 +53,21 @@ private void dfs1(List<List<Integer>> resultList, List<Integer> list, int n, int
5253
dfs1(resultList, newList, n / i, i);
5354

5455
newList.add(n / i);
55-
resultList.add(new ArrayList<Integer>(newList));
56+
resultList.add(newList);
57+
}
58+
}
59+
}
60+
61+
private void dfs2(List<List<Integer>> resultList, List<Integer> list, int n, int start) {
62+
for (int i = start; i * i < n; i++) {
63+
if (n % i == 0) {
64+
list.add(i);
65+
dfs2(resultList, list, n / i, i);
66+
67+
list.add(n / i);
68+
resultList.add(new ArrayList<Integer>(list));
69+
list.remove(list.size() - 1);
70+
list.remove(list.size() - 1);
5671
}
5772
}
5873
}

0 commit comments

Comments
 (0)