LeetCode: 216. 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.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations.
  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]]
  解题思路
深度优先搜索遍历所有情况。
AC 代码
class Solution {
    void combinationSum3(vector<vector<int>>& combinations, vector<int> record, int k, int n, int i)
    {
        if(n == 0 && k == 0)
        {
            combinations.push_back(record);
            return;
        }
        else if(n < 0 || k < 0 || i > 9)
        {
            return;
        }
        
        if(n >= i)
        {
            record.push_back(i);
            combinationSum3(combinations, record, k-1, n-i, i+1);
            record.pop_back();
        }
        
        combinationSum3(combinations, record, k, n, i+1);
    }
public:
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> ans;
        combinationSum3(ans, {}, k, n, 1);
        return ans;
    }
};

京公网安备 11010502036488号