5.排列组合
面试题08.08. 有重复字符串的排列组合
-
描述
有重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合。 示例1: 输入:S = "qqe" 输出:["eqq","qeq","qqe"] 示例2: 输入:S = "ab" 输出:["ab", "ba"] 提示: 字符都是英文字母。 字符串长度在[1, 9]之间。
-
思路
使用STL全排列函数,next_permutation会排序大于当前数字的数组组合。prev_permutation会排序小于当前数字的数组组合
-
代码
#include <iostream> using namespace std; #include <vector> #include <algorithm> class Solution { public: vector<string> permutation(string S) { vector<char> chars; chars.assign(S.begin(),S.end()); sort(chars.begin(),chars.end()); for(auto c : chars) { printf("%c ",c); } vector<string> res; string tmp; printf("\n"); do { for(int i = 0 ; i < S.size(); i++) { // printf("%c",chars[i]); tmp += chars[i]; } res.push_back(tmp); tmp = ""; // printf("\n"); } while (next_permutation(chars.begin(),chars.end())); return res; } }; int main() { string str; while(cin>>str) { cout << str << endl; if (getchar() == '\n') break; } Solution sol; vector<string> res; res = sol.permutation(str); for(auto s: res) { cout << s << " "; } cout << endl; return 0; }
leetcode 77.组合
-
描述
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。 你可以按 任何顺序 返回答案。 示例 1: 输入:n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] 示例 2: 输入:n = 1, k = 1 输出:[[1]] 提示: 1 <= n <= 20 1 <= k <= n
-
思路
深度优先算法,循环遍历范围内所有的数字添加到路径,再继续向内遍历
如果k(剩余额度)为0,将该路径添加到结果
-
代码
#include <iostream> using namespace std; #include <vector> #include <algorithm> #include <map> class Solution { vector<vector<int>> res; vector<int> tmp; public: vector<vector<int>> combine(int n, int k) { dfs(1, n, k); return res; } void dfs(int cur, int n, int k) { if (k == 0) { res.push_back(tmp); return; } for (int i = cur; i <= n - k + 1; i++) { tmp.push_back(i); dfs(i+1, n , k - 1); tmp.pop_back(); } } }; int main() { int n,k; cin >> n >> k; cout << n << " " << k << endl; Solution sol; vector<vector<int>> res; res = sol.combine(n,k); for(auto vec:res) { for(auto n:vec) printf("%d ",n); printf("\n"); } return 0; }