class Solution {
private:
vector<vector<int>> ans;
vector<int> s;
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<bool> visited(10, false);
dfs(visited, 1, k, n);
return ans;
}
void dfs(vector<bool> &visited, int currentMin, int k, int n){
if(k < 0 || n < 0) return;
if(n == 0){
if(k == 0)
ans.push_back(vector<int>(s.begin(), s.end()));
return;
}
if(k == 0) return;
if(currentMin > 9)
return;
int minSelect, maxSelect;
(minSelect = n - (k-1)*9) > currentMin? : (minSelect = currentMin);
maxSelect = (n >= 9? 9 : n);
while(minSelect <= maxSelect){
if(visited[minSelect]){
++minSelect;
continue;
}
s.push_back(minSelect);
visited[minSelect] = true;
dfs(visited, minSelect+1, k-1, n - minSelect);
s.pop_back();
visited[minSelect] = false;
++minSelect;
}
}
};
216. Combination Sum III
最新推荐文章于 2023-05-22 12:05:46 发布