组合总和III
回溯法无减枝
class Solution { public: vector<vector<int>> result; vector<int> path; void backtraking(int k, int n , int sum ,int startidx) { if(path.size() == k && sum == n) { result.push_back(path); return; }else { for(int i= startidx ; i < 10 ; i++) { path.push_back(i); backtraking(k,n,sum+i,i+1); path.pop_back(); } return; } } vector<vector<int>> combinationSum3(int k, int n) { backtraking(k,n,0,1); return result; } };
回溯剪枝
剪枝原理同 77题
class Solution { public: vector<vector<int>> result; vector<int> path; void backtraking(int k, int n , int sum ,int startidx) { if(sum > n) return; if(path.size() == k && sum == n) { result.push_back(path); return; }else { for(int i= startidx ; i < 10 - (k - path.size()) + 1 ; i++) { path.push_back(i); backtraking(k,n,sum+i,i+1); path.pop_back(); } return; } } vector<vector<int>> combinationSum3(int k, int n) { backtraking(k,n,0,1); return result; } };
二刷
class Solution { public: vector<vector<int>> result; vector<int> pathNum; void dfs(int k , int n , int sum ,int fir) { if(pathNum.size() == k && sum == n) { result.push_back(pathNum); return; } for(int i = fir ; i<=9 ; i++) { pathNum.push_back(i); dfs(k,n,sum+i,i+1); pathNum.pop_back(); } } vector<vector<int>> combinationSum3(int k, int n) { dfs(k,n,0,1); return result; } };