11.29 log

17.电话号码的字母组合

class Solution {
private:
    const string letterMap[10]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    string path;
    vector result;
    void backtracking(string digits,int startIndex){
        if(path.size()==digits.size()){
            result.push_back(path);
            return;
        }
        string letter=letterMap[digits[startIndex]-'0'];
        for(char c:letter){
            path.push_back(c);
            backtracking(digits,startIndex+1); 
            path.pop_back();
        }
        return;
    }
public:
    vector letterCombinations(string digits){
        if(digits.size()==0) return result;
        backtracking(digits,0);
        return result;
    }
};

递归参数为号码,起始下标,返回值无;递归终止条件为当path的size大小等于号码size的大小时,result记录path并返回;单层遍历逻辑为先表示出单层的letter,然后用for循环横向遍历,用path记录字符,然后递归,后回溯,path弹出字符。

39. 组合总和

class Solution {
private:
    vector path;
    vector> result;
    void backtracking(vector& candidates,int target,int Sum,int startIndex){
        if(Sum>=target){
            if(Sum==target) result.push_back(path);
            return;
        }
        for(int i=startIndex;i> combinationSum(vector& candidates, int target) {
        backtracking(candidates,target,0,0);
        return result;
    }
};

递归的参数为整数数组,目标和,数字和,起始下标;终止条件,当数字和大于等于目标和时返回,当梳子和等于目标和时,result记录该path;单层递归逻辑为,用for循环横向遍历,i的起始值为startIndex, path记录该点数组的值,然后递归,传入startIndex的值为i,因为一个数字可以重复取多次,Sum传入Sum+节点值,因为是形参,所以递归return之后自动回溯,path弹出节点值 

你可能感兴趣的:(java,算法,开发语言)