Combination Sum

描述

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1,a2,…,aka_1, a_2, …, a_ka​1​​,a​2​​,…,a​k​​) must be in non-descending order. (ie, a1≤a2≤…≤aka_1 \leq a_2 \leq … \leq a_ka​1​​≤a​2​​≤…≤a​k​​).
  • The solution set must not contain duplicate combinations.
    For example, given candidate set 2,3,6,7 and target 7, A solution set is:
  1. [7]
  2. [2, 2, 3]

分析

代码

  1. // Combination Sum
  2. // 时间复杂度O(n!),空间复杂度O(n)
  3. class Solution {
  4. public:
  5. vector<vector<int> > combinationSum(vector<int> &nums, int target) {
  6. sort(nums.begin(), nums.end());
  7. vector<vector<int> > result; // 最终结果
  8. vector<int> path; // 中间结果
  9. dfs(nums, path, result, target, 0);
  10. return result;
  11. }
  12. private:
  13. void dfs(vector<int>& nums, vector<int>& path, vector<vector<int> > &result,
  14. int gap, int start) {
  15. if (gap == 0) { // 找到一个合法解
  16. result.push_back(path);
  17. return;
  18. }
  19. for (size_t i = start; i < nums.size(); i++) { // 扩展状态
  20. if (gap < nums[i]) return; // 剪枝
  21. path.push_back(nums[i]); // 执行扩展动作
  22. dfs(nums, path, result, gap - nums[i], i);
  23. path.pop_back(); // 撤销动作
  24. }
  25. }
  26. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/dfs/combination-sum.html