DAY28
216组合总和-iii
未剪枝,注意i=startindex开始:
- class Solution {
- private:
- vector<vector<int>> result;
- vector<int> path;
- void backtracking(int k,int sum,int targetsum,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,sum,targetsum,i+1);
- sum-=i;
- path.pop_back();
- }
- return ;
- }
- public:
- vector<vector<int>> combinationSum3(int k, int n) {
- result.clear();
- path.clear();
- backtracking(k,0,n,1);
- return result;
- }
- };
剪枝版:
- class Solution {
- private:
- vector<vector<int>> result;
- vector<int> path;
- void backtracking(int k,int sum,int targetsum,int startindex){
- if(path.size()==k){
- if(sum==targetsum){
- result.push_back(path);
- }
- return;
- }
- for(int i=startindex;i<=9-(k-path.size())+1;i++)
- {
- sum+=i;
- path.push_back(i);
- if(sum>targetsum){
- sum-=i;
- path.pop_back();
- return;
- }
- backtracking(k,sum,targetsum,i+1);
- sum-=i;
- path.pop_back();
- }
- return ;
- }
- public:
- vector<vector<int>> combinationSum3(int k, int n) {
- result.clear();
- path.clear();
- backtracking(k,0,n,1);
- return result;
- }
- };
17电话号码的字母组合
- class Solution {
- private:
- vector<string> map={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
- vector<string> result;
- string s;
- void backtracking(string digits,int index){
- //待二刷
- if(index==digits.size()){
- result.push_back(s);
- return ;
- }
- int digit=digits[index]-'0';
- string letters=map[digit];
- for(int i=0;i<letters.size();i++){
- s.push_back(letters[i]);
- backtracking(digits,index+1);
- s.pop_back();
- }
- }
- public:
- vector<string> letterCombinations(string digits) {
- s.clear();
- result.clear();
- if(digits.size()==0){
- return result;
- }
- backtracking(digits,0);
- return result;
- }
- };