Combination Sum III

xiaoxiao2021-02-27  562

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

方法:DFS

class Solution { private: void find(vector<vector<int>>& res, vector<int>& buffer, int index,int temp_sum, int count_number, int k,int n){ if(count_number > k || temp_sum > n){ return; } if(count_number == k && temp_sum == n){ res.push_back(buffer); return ; } for(int i = index ; i < 10; ++i){ buffer.push_back(i); find(res,buffer,i+1,temp_sum + i,count_number+1,k,n); buffer.pop_back(); } } public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> res; vector<int> buffer; find(res,buffer,1,0,0,k,n); return res; } };
转载请注明原文地址: https://www.6miu.com/read-682.html

最新回复(0)