Leetcode: Combination Sum III

来源:互联网 发布:网络安全法手抄报内容 编辑:程序博客网 时间:2024/05/17 01:01


Find all possible combinations of k numbers that add up to a numbern, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]


Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

跟前面几个类似,DFS,不过可以剪枝 - 一旦找到了一个组合,后面的就不需要再考虑了。应该还可以继续优化,或者考虑一下数学公式。

class Solution {public:    vector<vector<int>> combinationSum3(int k, int n) {        if (n <= 0 || k <= 0) {            return result;        }                vector<int> nums{1, 2, 3, 4, 5, 6, 7, 8, 9};        vector<int> curComb;        combUtil(nums, curComb, 0, k, n);                return result;    }        bool combUtil(const vector<int>& nums, vector<int>& curComb, int start, int k, int target) {        if (target == 0 && k == 0) {            result.push_back(curComb);            return false;        }                if (target <= 0) {            return false;        }        if (k <= 0) {            return true;        }                for (int i = start; i < nums.size(); ++i) {            curComb.push_back(nums[i]);            bool shouldContinue = combUtil(nums, curComb, i + 1, k - 1, target - nums[i]);            curComb.pop_back();            if (!shouldContinue) {                break;            }        }                return true;    }    private:    vector<vector<int>> result;};

0 0
原创粉丝点击