Leetcode: 216. Combination Sum III(Week14, Medium)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linwh8/article/details/78769242

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

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]]

  • 题意:定义k为组合的长度,n为目标值,现要求从数字序列1-9中,找到所有的组合(组合不重复),且数字序列中每个数字只能使用一次,最终每个组合的和会等于目标值
  • 思路:思路与Combination SumII类似,只不过是在递归函数中要多加点限制,即获得正确组合的条件是:n==0 && k == 0
  • 代码如下:
class Solution {
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> result;
        vector<int> temp_result;
        for (int i = 1; i <= 9; i++) {
            temp_result.push_back(i);
            solve_Combination_Sum(result, temp_result, k-1, n-i, i);
            temp_result.pop_back();
        }
        return result;
    }
    void solve_Combination_Sum(vector<vector<int>>& result, vector<int>& out, int k, int n, int num) {
        if (n < 0) return;
        if (n == 0 && k == 0) result.push_back(out);
        if (k == 0) return;
        for (int i = num+1; i <= 9; i++) {
            out.push_back(i);
            solve_Combination_Sum(result, out, k-1, n-i, i);
            out.pop_back();
        }
    }
};

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!

猜你喜欢

转载自blog.csdn.net/linwh8/article/details/78769242