Skip to content

Java Chapter 14: Backtracking #69

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions java/Backtracking/CombinationsOfSumK.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import java.util.ArrayList;
import java.util.List;

public class CombinationsOfSumK {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result -> res

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice catch!

public List<List<Integer>> combinationsOfSumK(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
dfs(new ArrayList<>(), 0, nums, target, res);
return res;
}

private void dfs(List<Integer> combination, int startIndex, int[] nums, int target, List<List<Integer>> res) {
// Termination condition: If the target is equal to 0, we found a combination
// that sums to 'k'.
if (target == 0) {
res.add(new ArrayList<>(combination));
return;
}
// Termination condition: If the target is less than 0, no more valid
// combinations can be created by adding it to the current combination.
if (target < 0) {
return;
}
// Starting from start_index, explore all combinations after adding nums[i].
for (int i = startIndex; i < nums.length; i++) {
// Add the current number to create a new combination.
combination.add(nums[i]);
// Recursively explore all paths that branch from this new combination.
dfs(combination, i, nums, target - nums[i], res);
// Backtrack by removing the number we just added.
combination.remove(combination.size() - 1);
}
}
}
34 changes: 34 additions & 0 deletions java/Backtracking/FindAllPermutations.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FindAllPermutations {
public List<List<Integer>> findAllPermutations(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(nums, new ArrayList<>(), new HashSet<>(), res);
return res;
}

private void backtrack(int[] nums, List<Integer> candidate, Set<Integer> used, List<List<Integer>> res) {
// If the current candidate is a complete permutation, add it to the
// result.
if (candidate.size() == nums.length) {
res.add(new ArrayList<>(candidate));
return;
}
for (int num : nums) {
if (!used.contains(num)) {
// Add 'num' to the current permutation and mark it as used.
candidate.add(num);
used.add(num);
// Recursively explore all branches using the updated
// permutation candidate.
backtrack(nums, candidate, used, res);
// Backtrack by reversing the changes made.
candidate.remove(candidate.size() - 1);
used.remove(num);
}
}
}
}
27 changes: 27 additions & 0 deletions java/Backtracking/FindAllSubsets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.util.ArrayList;
import java.util.List;

public class FindAllSubsets {
public List<List<Integer>> findAllSubsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(0, new ArrayList<>(), nums, res);
return res;
}

private void backtrack(int i, List<Integer> currSubset, int[] nums, List<List<Integer>> res) {
// Base case: if all elements have been considered, add the
// current subset to the output.
if (i == nums.length) {
res.add(new ArrayList<>(currSubset));
return;
}
// Include the current element and recursively explore all paths
// that branch from this subset.
currSubset.add(nums[i]);
backtrack(i + 1, currSubset, nums, res);
// Exclude the current element and recursively explore all paths
// that branch from this subset.
currSubset.remove(currSubset.size() - 1);
backtrack(i + 1, currSubset, nums, res);
}
}
41 changes: 41 additions & 0 deletions java/Backtracking/NQueens.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.HashSet;
import java.util.Set;

public class NQueens {
int res = 0;

public int nQueens(int n) {
dfs(0, new HashSet<>(), new HashSet<>(), new HashSet<>(), n);
return res;
}

private void dfs(int r, Set<Integer> diagonalsSet, Set<Integer> antiDiagonalsSet, Set<Integer> colsSet, int n) {
// Termination condition: If we have reached the end of the rows,
// we've placed all 'n' queens.
if (r == n) {
res++;
return;
}
for (int c = 0; c < n; c++) {
int currDiagonal = r - c;
int currAntiDiagonal = r + c;
// If there are queens on the current column, diagonal or
// anti-diagonal, skip this square.
if (colsSet.contains(c) || diagonalsSet.contains(currDiagonal) || antiDiagonalsSet.contains(currAntiDiagonal)) {
continue;
}
// Place the queen by marking the current column, diagonal, and
// anti−diagonal as occupied.
colsSet.add(c);
diagonalsSet.add(currDiagonal);
antiDiagonalsSet.add(currAntiDiagonal);
// Recursively move to the next row to continue placing queens.
dfs(r + 1, diagonalsSet, antiDiagonalsSet, colsSet, n);
// Backtrack by removing the current column, diagonal, and
// anti−diagonal from the hash sets.
colsSet.remove(c);
diagonalsSet.remove(currDiagonal);
antiDiagonalsSet.remove(currAntiDiagonal);
}
}
}
42 changes: 42 additions & 0 deletions java/Backtracking/PhoneKeypadCombinations.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PhoneKeypadCombinations {
public List<Stirng> phoneKeypadCombinations(String digits) {
Map<Character, String> keypadMap = new HashMap<>();
keypadMap.put('2', "abc");
keypadMap.put('3', "def");
keypadMap.put('4', "ghi");
keypadMap.put('5', "jkl");
keypadMap.put('6', "mno");
keypadMap.put('7', "pqrs");
keypadMap.put('8', "tuv");
keypadMap.put('9', "wxyz");
List<String> result = new ArrayList<>();
backtrack(0, new ArrayList<>(), digits, keypadMap, result);
return result;
}

private void backtrack(int i, List<Character> currCombination, String digits, Map<Character, String> keypadMap, List<String> result) {
// Termination condition: if all digits have been considered, add the
// current combination to the output list.
if (currCombination.size() == digits.length()) {
StringBuilder sb = new StringBuilder();
for (char c: currCombination) {
sb.append(c);
}
result.add(sb.toString());
return;
}
for (char letter: keypadMap.get(digits.charAt(i)).toCharArray()) {
// Add the current letter.
currCombination.add(letter);
// Recursively explore all paths that branch from this combination.
backtrack(i + 1, currCombination, digits, keypadMap, result);
// Backtrack by removing the letter we just added.
currCombination.remove(currCombination.size() - 1);
}
}
}