-
Notifications
You must be signed in to change notification settings - Fork 89
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
Destiny-02
merged 6 commits into
ByteByteGoHq:main
from
Jer3myYu:java-solutions-backtracking
Feb 6, 2025
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
bc1c0f7
add: FindAllPermutations
Jer3myYu ac3691b
add: FindAllSubsets
Jer3myYu 085ab5a
add: NQueens
Jer3myYu 767ed0f
add: CombinationsOfSumK
Jer3myYu d25a493
add: PhoneKeypadCombinations
Jer3myYu 9bac83d
fix: result to res
Jer3myYu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
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); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
result
->res
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nice catch!