Backtracking Leetcode Summary, Part 2
- Subsets
- Palindrome
- Combination Sum, repeated number used
- Combination Sum, unique number used
Subsets:
Problem Description: Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets.
Few Key Points:
- This algorithm is very close to that of permutation. The only difference is that this counts for subsets instead of permutations.
- One of the key point is to keep the order, don’t permute like the permutation algorithm
Code:
backtracking part, takes parameters:
- result: LinkedList>
- current: ArrayList
- nums: nums to extract from
- cur_idx: current index
Note: when adding to result, convert the current list into a new listThe solution part:1
2
3
4
5
6
7
8
9
10
11public void backtrack(List<List<Integer>> l,
List<Integer> tmpList,
int [] nums,
int start) {
l.add(new ArrayList<>(tmpList));
for (int i = start; i < nums.length; i++) {
tmpList.add(nums[i]);
backtrack(l, tmpList, nums, i+1);
tmpList.remove(tmpList.size() - 1);
}
}1
2
3
4
5
6
7public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
List<Integer> tmp = new ArrayList<Integer>();
int start = 0;
backtrack(res, tmp, nums, start);
return res;
}
Palindrome:
Problem Description: Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
e.g.:
Input: “aab”
Output:
[[“aa”,”b”],
[“a”,”a”,”b”]]
Few Key Points:
An utility function can be used to determine if str is palindrome or not.
Code:
backtrack:
1 | public void backtrack(List<List<String>> result, |
Check if str is palindrome:
1 | public boolean isPalindrome(String str, int s, int e) { |
The solution part:
1 | public List<List<String>> partition(String s) { |
Combination Sum, repeat allowed
Problem Description: Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times.
e.g.:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[[7],
[2,2,3]]
Codes:
backtrack:
1 | public void backtrack(List<List<Integer>> res, |
The solution part:
1 | public List<List<Integer>> combinationSum(int[] candidates, int target) { |
Combination Sum, no repeats
Problem Description: Same as combination sum, with only difference that each number can only be used once.
Codes:
backtrack: (added while loop to eliminate repeating results)
1 | public void backtrack(List<List<Integer>> res, |
The solution part is the same as the last section.