Created
September 14, 2022 16:32
-
-
Save haixinsong/2f63e1635d596773fc79a9d68d2c0c13 to your computer and use it in GitHub Desktop.
small combine function
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
| #include <vector> | |
| #include <string> | |
| template <typename T> | |
| void combineInner(const std::vector<T> &data, int start, int m, int depth, std::vector<T> &temp, std::vector<std::vector<T>> &result) | |
| { | |
| if (depth > m - 1) | |
| return; | |
| if (depth == m - 1) | |
| { | |
| for (std::size_t i = start; i < data.size(); ++i) | |
| { | |
| temp[depth] = data[i]; | |
| result.push_back(temp); | |
| } | |
| } | |
| else | |
| { | |
| for (std::size_t i = start; i < data.size(); ++i) | |
| { | |
| temp[depth] = data[i]; | |
| combineInner(data, i + 1, m, depth + 1, temp, result); | |
| } | |
| } | |
| } | |
| // choose m item from data, put all the result to result_list | |
| template <typename T> | |
| void combine(const std::vector<T> &data, std::size_t m, std::vector<std::vector<T>> &result_list) | |
| { | |
| result_list.clear(); | |
| if (m <= 0 || data.size() < m) | |
| return; | |
| if (data.size() == m) | |
| { | |
| result_list.push_back(data); | |
| return; | |
| } | |
| int depth = 0; | |
| std::vector<T> temp(m, T()); | |
| combineInner(data, 0, m, depth, temp, result_list); | |
| } | |
| // g++ -g -std=c++11 -Wall -Wextra -o a.out combine.cpp | |
| int main() | |
| { | |
| { | |
| std::vector<int> a = {1, 2, 1, 4}; | |
| std::vector<std::vector<int>> result; | |
| combine(a, 0, result); | |
| assert(result.size() == 0); | |
| } | |
| { | |
| std::vector<int> a = {1, 2, 1, 4}; | |
| std::vector<std::vector<int>> result; | |
| combine(a, 1, result); | |
| assert(result.size() == 4); | |
| } | |
| { | |
| std::vector<int> a = {1, 2, 1, 4}; | |
| std::vector<std::vector<int>> result; | |
| combine(a, 2, result); | |
| assert(result.size() == 6); | |
| } | |
| { | |
| std::string s("ABCDEF"); | |
| std::vector<char> vchar(s.begin(), s.end()); | |
| std::vector<std::vector<char>> result; | |
| combine(vchar, 2, result); | |
| assert(result.size() == 15); | |
| for (std::vector<char> item : result) | |
| { | |
| std::string s1(item.begin(), item.end()); | |
| // std::cout << s1 << std::endl; | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment