216.组合总和|||
思路:这题和77题的组合思路差不多一样,只是多了一步判断加起来的和是否和目标值相等,并且回溯需要把相应的值减去。
代码:
vector<vector<int>> result;vector<int> path;void backtracking(int k,int targetSum,int sum,int startIndex){if(path.size() == k){if(sum == targetSum){result.push_back(path);return;}}for(int i = startIndex;i <= 9;i++){sum += i;path.push_back(i);backtracking(k,targetSum,sum,i++);sum -= i;path.pop_back();}}vector<vector<int>> combinationSum3(int k, int n) {backtracking(k,n,0,1);return result;}
剪纸优化:
优化1:如果当前sum值已经比目标值大了就没必要再继续递归了,因为按递归规则越往下加的数越大,当前sum已经超过了目标值,后面加说明数都超过目标值。
优化2:和77题的优化思路一样,i是控制起点,如果起点到终点之间的数不够k个则不需要再往下遍历。
代码:
vector<vector<int>> result;vector<int> path;void backtracking(int k,int targetSum,int sum,int startIndex){if(sum > targetSum){//优化1return;}if(path.size() == k){if(sum == targetSum){result.push_back(path);return;}}for(int i = startIndex;i <= 9 - (k - path.size()) + 1;i++){//优化2sum += i;path.push_back(i);backtracking(k,targetSum,sum,i+1);sum -= i;path.pop_back();}}vector<vector<int>> combinationSum3(int k, int n) {result.clear();path.clear();backtracking(k,n,0,1);return result;}