这两道题的基本思路和combination那一题是一致的,也是分治的方法。
其中combination Sum复杂一点,因为每个数可能用多次。仔细分析下,本质上也是一样的。原来是每个数仅两种可能。现在每个数有k +1中可能,k = target / i。
所以就是把简单的if else 分支变成for循环:
vector<vector<int> > combHelper(vector<int>::iterator first, vector<int>::iterator last, int target){ vector<vector<int>> result; if (target <= 0 || last == first) return result; if (*(last - 1) == target){ vector<int> vi; vi.push_back(target); result.push_back(vi); auto r2 = combHelper(first, last - 1, target); for (auto it = r2.begin(); it != r2.end(); it++) result.push_back(*it); } else if (*(last - 1) < target){ auto r1 = combHelper(first, last - 1, target - *(last - 1)); for (auto it = r1.begin(); it != r1.end(); it++){ it->push_back(*(last - 1)); result.push_back(*it); } auto r2 = combHelper(first, last - 1, target); for (auto it = r2.begin(); it != r2.end(); it++) result.push_back(*it); } else { auto r2 = combHelper(first, last - 1, target); for (auto it = r2.begin(); it != r2.end(); it++) result.push_back(*it); } return result; } vector<vector<int> > combinationSum2(vector<int> &num, int target) { sort(num.begin(), num.end()); auto result = combHelper(num.begin(), num.end(), target); if (!result.empty()){ sort(result.begin(), result.end()); auto it = unique(result.begin(), result.end()); result.erase(it, result.end()); } return result; }