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, 0, 0); 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 + 1; i < 10; ++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 == 1) return ret; if (num < 7 && num > 1) { ret.push_back('a' + (num - 2) * 3); ret.push_back('a' + (num - 2) * 3 + 1); ret.push_back('a' + (num - 2) * 3 + 2); } else if (num == 7) { ret.push_back('p'); ret.push_back('p' + 1); ret.push_back('p' + 2); ret.push_back('p' + 3); } else if (num == 8) { ret.push_back('t'); ret.push_back('t' + 1); ret.push_back('t' + 2); } else if (num == 9) { ret.push_back('w'); ret.push_back('w' + 1); ret.push_back('w' + 2); ret.push_back('w' + 3); } return ret; } void dfs(string& s, int t, string &d) { if (t == d.size() && s.size() > 0) { ret.push_back(s); return; } vector<char> cs = getChar(d[t] - '0'); for (int i = 0; i < cs.size(); ++i) { s.push_back(cs[i]); dfs(s, t + 1, d); s.pop_back(); } } vector<string> letterCombinations(string& digits) { // Write your code here string s = ""; dfs(s, 0, digits); return ret; } };
总想把每一篇文章精雕细琢之后以完美的面貌示人,就像演员在演出前都要彩排,总想准备好之后再去展现精彩的一面,但人生的每一刻都是精彩的,就算现在还不完善也要发出来,作为自己一直在学习的一种见证。