https://leetcode.com/problems/combination-sum-iii/
用dfs枚举。
class Solution {
public:
int kk, nn;
vector<vector<int>> res;
vector<vector<int>> combinationSum3(int k, int n) {
kk = k, nn = n;
vector<int> r;
dfs(r, , );
return res;
} void dfs(vector<int> &a, int t, int sum) {
if (a.size() >= kk || sum >= nn) {
if (a.size() == kk && sum == nn) {
res.push_back(a);
}
return;
}
for (int i = t + ; i < ; ++i) {
a.push_back(i);
dfs(a, i, sum + i);
a.pop_back();
}
}
};
其他同类题:
http://www.jiuzhang.com/solutions/search/?question=Combination+Sum
1. http://www.lintcode.com/zh-cn/problem/letter-combinations-of-a-phone-number/
class Solution {
public:
vector<string> ret; vector<char> getChar(int num) {
vector<char> ret;
if (num == ) return ret;
if (num < && num > ) {
ret.push_back('a' + (num - ) * );
ret.push_back('a' + (num - ) * + );
ret.push_back('a' + (num - ) * + );
} else if (num == ) {
ret.push_back('p');
ret.push_back('p' + );
ret.push_back('p' + );
ret.push_back('p' + );
} else if (num == ) {
ret.push_back('t');
ret.push_back('t' + );
ret.push_back('t' + );
} else if (num == ) {
ret.push_back('w');
ret.push_back('w' + );
ret.push_back('w' + );
ret.push_back('w' + );
}
return ret;
} void dfs(string& s, int t, string &d) {
if (t == d.size() && s.size() > ) {
ret.push_back(s);
return;
}
vector<char> cs = getChar(d[t] - '');
for (int i = ; i < cs.size(); ++i) {
s.push_back(cs[i]);
dfs(s, t + , d);
s.pop_back();
}
} vector<string> letterCombinations(string& digits) {
// Write your code here
string s = "";
dfs(s, , digits);
return ret;
}
};