From efb3ce0e0ababa1807fdd32b1b6dea829ef6c9cf Mon Sep 17 00:00:00 2001 From: Brijesh Kumar Date: Thu, 1 Oct 2020 14:49:35 +0530 Subject: [PATCH] added backtracking algorithm named all permutations --- .../backtracking/all_permutations.hpp | 51 +++++++++++++++++++ .../backtracking/all_permutations.cpp | 29 +++++++++++ 2 files changed, 80 insertions(+) create mode 100644 cpp/include/algorithm/backtracking/all_permutations.hpp create mode 100644 cpp/test/algorithm/backtracking/all_permutations.cpp diff --git a/cpp/include/algorithm/backtracking/all_permutations.hpp b/cpp/include/algorithm/backtracking/all_permutations.hpp new file mode 100644 index 00000000..b4b3e96e --- /dev/null +++ b/cpp/include/algorithm/backtracking/all_permutations.hpp @@ -0,0 +1,51 @@ +/* + Printing all the permutations of a string/array + -------------------- + A permutation, also called an “arrangement number” or “order,” is a rearrangement + of the elements of an ordered list S into a one-to-one correspondence with S itself. + A string of length n has n! permutation. Generate all the permutations of the string. + + Time complexity + --------------- + O(N*N!), where N is the length of the string. + + Space complexity + ---------------- + O(N!), where N is the length of the string. + + Author + ------ + Brijesh Kumar (@brijeshsos66) +*/ + +#ifndef ALL_PERMUTATIONS_HPP +#define ALL_PERMUTATIONS_HPP + +#include + +/* +Below is the program for printing the permutations of a string. Inorder to perform the same on a array/vector +then convert the array elements into string(using to_string() function) and perform the same. +Here start is the starting point of a string intially equals to 0 and end is initially equals to length of the +string minus 1 (N - 1) as indices are starting from 0. +*/ +void permutations(string str, int start, int end){ + //BASE case + if(start == end) + cout< permutations = {""}; + REQUIRE(all_permutations(s,0,s.length()-1) == permutations); + + s = "a"; + permutations = {"a"}; + REQUIRE(all_permutations(s,0,s.length()-1) == permutations); + + s = " "; + permutations = {" "}; + REQUIRE(all_permutations(s,0,s.length()-1) == permutations); +} + + TEST_CASE("Normal cases",[backtracking][all_permutations]"){ + string s = "abc"; + vector permutations = {"abc","acb","bac","bca","cab","cba"}; + REQUIRE(all_permutations(s,0,s.length()-1) == permutations); + + s = "abcd"; + permutations ={"abcd","abdc","acbd","acdb","adcb","adbc", + "bacd","badc","bcad","bcda","bdca","bdac", + "cbad","cbda","cabd","cadb","cdab","cdba", + "dbca","dbac","dcba","dcab","dacb","dabc" }; + REQUIRE(all_permutations(s,0,s.length()-1) == permutations); +} \ No newline at end of file