LeetCode 17. Letter Combinations of a Phone Number

暴搜。

void DFS(int pos,string di,string temp,vector<string> &ans){
    if (pos==0) {ans.push_back(temp);return;}
    string m[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    int len=m[di[0]-'2'].length();
    while(len--){
        DFS(pos-1,di.substr(1,pos-1),temp+m[di[0]-'2'][len],ans);
    }
}

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        int len=digits.length();
        if(digits.empty()) return vector<string>();
        vector<string> ans;
        DFS(len,digits+" ","",ans);
        return ans;
    }
};

 

这道题本来我以为是一道深搜,但是看着这个递归程序感觉既像DFS,又像BFS...(我对比了一下应该是DFS -> reference)

但是递归有可能会爆栈,所以可以将递归形式的DFS借助队列转换成非递归形式的BFS。以下是discuss中的两个例子。

 

vector<string> letterCombinations(string digits) {
    vector<string> res;
    string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    res.push_back("");
    for (int i = 0; i < digits.size(); i++)
    {
        vector<string> tempres;
        string chars = charmap[digits[i] - '0'];
        for (int c = 0; c < chars.size();c++)
            for (int j = 0; j < res.size();j++)
                tempres.push_back(res[j]+chars[c]);
        res = tempres;
    }
    return res;
}

 

public List<String> letterCombinations(String digits) {
        LinkedList<String> ans = new LinkedList<String>();
        if(digits.isEmpty()) return ans;
        String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        ans.add("");
        while(ans.peek().length()!=digits.length()){
            String remove = ans.remove();
            String map = mapping[digits.charAt(remove.length())-'0'];
            for(char c: map.toCharArray()){
                ans.addLast(remove+c);
            }
        }
        return ans;
    }

 

posted @ 2018-08-09 23:28  Travelller  阅读(99)  评论(0编辑  收藏  举报