[leetcode] 216. Combination Sum III 解题报告

题目链接:https://leetcode.com/problems/combination-sum-iii/

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.

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的题目。一个数可以拿,可以不拿,因此用DFS+回溯,将符合条件的答案都加入到结果中去。

代码如下:

class Solution {
public:
    void DFS(vector<int> tem, int k, int n, int index, int sum)
    {
        tem.push_back(index);
        if(index > 9 || tem.size() > k) return;
        if(tem.size() == k && index + sum == n)//如果当前结果满足条件,加入到集合中
        {
            result.push_back(tem);
            return;
        }
        DFS(tem, k, n, index+1, sum+index);//拿当前的一个
        tem.pop_back();
        DFS(tem, k, n, index+1, sum);//不拿当前的一个
    }
    
    vector<vector<int>> combinationSum3(int k, int n) {
        if(k < 1 || n < 1)  return result;
        vector<int> tem;
        DFS(tem, k, n, 1, 0);
        return result;
    }
private:
    vector<vector<int>> result;
};


你可能感兴趣的:(LeetCode,算法,DFS,backtracking)