to do
8.5.2] Combinations ite
耶昨天学的dfs+backtracking还是有用哒
void combineR(int start, int n, int k, vector<int>& path, vector<vector<int>>& ret) {
if (path.size()==k) {
ret.push_back(path);
return;
}
for (int i=start; i<=n; ++i) {
path.push_back(i);
combineR(i+1, n, k, path, ret);
path.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
if (k>n) return vector<vector<int>> {};
vector<int> path;
vector<vector<int>> ret;
combineR(1, n, k, path, ret);
return ret;
}
8.5.2] rec w/ math equ
C(n,k)=C(n-1,k-1)+C(n-1,k)
60%. Note that I initially didif (k==0||k>n) return vec<vec<int>>{};
This will cause missing elems.
vector<vector<int>> combine(int n, int k) {
if (k>n) return vector<vector<int>>{};
vector<int> vec;
if (k==n || k==0) {
for (int i=1; i<=k; ++i) vec.push_back(i);
return vector<vector<int>> {vec};
}
auto ret1 = combine(n-1, k-1);
for_each(ret1.begin(), ret1.end(), [n](vector<int>& v){
v.push_back(n);}); // need to capture n
auto ret2 = combine(n-1, k);
ret1.insert(ret1.begin(), ret2.begin(), ret2.end());
return ret1;
}
8.6.1] rec Letter Combinations of a Phone Number
note using vector<string> keypads {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void letterR(vector<string>& keypads, string digits, string& path, vector<string>& ret) {
if (path.size()==digits.size()) {
ret.push_back(path);
return;
}
string letters = keypads[digits[path.size()]-'0'];
for (int i=0; i<letters.size(); ++i) {
path.push_back(letters[i]);
letterR(keypads, digits, path, ret);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
vector<string> ret;
if (digits=="") return ret;
vector<string> keypads {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
string path;
letterR(keypads, digits, path, ret);
return ret;
}
8.6.2] ite Letter Combinations of a Phone Number
写一写找规律,然而看了答案;(
vector<string> letterCombinations(string digits) {
if (digits.empty()) return vector<string>{};
const vector<string> keypads {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> ret {""};
for (int i=0; i<digits.size(); ++i) {
string keypad = keypads[digits[i]-'0'];
vector<string> ret_base = std::move(ret);
ret.clear();
for (int j=0; j<keypad.size(); ++j) {
vector<string> toInsert = ret_base;
char c = keypad[j];
for (string& str : toInsert) {
str.push_back(c);
}
ret.insert(ret.end(), toInsert.begin(), toInsert.end());
}
}
return ret;
}