Below you will find pages that utilize the taxonomy term “BACKTRACKING”
Posts
Backtracking
INFO It’s an Algorithm to permute string. Usefull to find all the possible permutations
EXAMPLE Steps Create a function which take the string, the first index and the last index: If start and end index are the same, end of the algorithm (print or return depends on what you wants) Otherwise, loop on each index between start and end: Swap string at index start and string at index i of loop Call the function with as first index the first index + 1 Swap again string at index start and string at index i of loop Code #include <iostream> #include <string> void backtrack(std::string &s, int idx, int N) { if (idx == N) std::cout << s << std::endl; else { for (int i = idx; i <= N; i++) { std::swap(s[idx], s[i]); backtrack(s, idx + 1, N); // Reset std::swap(s[idx], s[i]); } } } int main(int ac, char *av[]) { std::string s = "ABC"; int n = s.
read morePosts
Letter Case Permutation
PROBLEM Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
Example1 *Input*: s = "a1b2" *Output*: ["a1b2","a1B2","A1b2","A1B2"] Example2 *Input*: s = "3z4" *Output*: ["3z4","3Z4"] Constraints s consits of lowercase English letters, uppercase English letters and digits SOLVING we’ll use Backtracking method.
Steps If the index equal to size push to the result the string Call once the method with the exact same string and just the index + 1 If the current element is an alpha change uppercase <–> lowercase and call a second time the method Return the result Code class Solution { public: vector<string> letterCasePermutation(string s) { vector<string> result; backtrack(s, 0, s.
read morePosts
Permutation
PROBLEM Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example1 *Input*: nums = [1,2,3] *Output*: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example2 *Input*: nums = [0,1] *Output*: [[0,1],[1,0]] Example3 *Input*: nums = [1] *Output*: [ [1] ] Constraints 1<=nums.length<=6 -10<=nums[i]<=10 All the integers of nums are unique. SOLVING we’ll use Backtracking method
Steps Backtracking method: push in result and return if current index equal size for each index between current index and size: swap in nums the element at current index and index from for loop call in recursive the backtrack method with as parameter current index + 1 re swap in nums the element at current index and index from for loop to reset the change return result Code class Solution { public: vector<vector<int>> permute(vector<int> &nums) { backtrack(nums, 0, nums.
read more