Leetcode 17. Letter Combinations of a Phone Number

我的做法是利用迭代来代替递归
本质这个是一个尾递归结构,跟数数是一个道理

public class Solution {
    public List letterCombinations(String digits) {
        List result = new ArrayList<>();
        int[] digitCount = new int[10];
        for (int i = 0; i< 10 ; i++) {
            digitCount[i] = 0;
        }
        int length = digits.length();
        for (int i = 0; i < length; i++) {
            int d = digits.charAt(i) - 48;
            digitCount[d] = digitCount[d] + 1;
        }
        if (digitCount[0] > 0 || digitCount[1] > 0) {
            return result;
        }

        List digitArray = new ArrayList<>();
        for (int i = 0; i char2 = Arrays.asList('a', 'b', 'c');
        List char3 = Arrays.asList('d', 'e', 'f');
        List char4 = Arrays.asList('g', 'h', 'i');
        List char5 = Arrays.asList('j', 'k', 'l');
        List char6 = Arrays.asList('m', 'n', 'o');
        List char7 = Arrays.asList('p', 'q', 'r', 's');
        List char8 = Arrays.asList('t', 'u', 'v');
        List char9 = Arrays.asList('w', 'x', 'y', 'z');
        List> charMap = new ArrayList>();
        charMap.add(char2);
        charMap.add(char3);
        charMap.add(char4);
        charMap.add(char5);
        charMap.add(char6);
        charMap.add(char7);
        charMap.add(char8);
        charMap.add(char9);
        int[] pointer = new int[digitArray.size()];
        for (int i = 0; i< digitArray.size();i++) {
            pointer[i]=0;
        }
        int p = digitArray.size()-1;
        while(p >= 0) {
            if (p == digitArray.size()-1 && pointer[digitArray.size()-1] < charMap.get(digitArray.get(digitArray.size()-1)-2).size()) {
                char[] resultChars = new char[digitArray.size()];
                for (int i=0;i

看到更加优雅的一个解法

public List letterCombinations(String digits) {  
        List result = new ArrayList();  
        if(digits.isEmpty()) {  
            result.add("");  
            return result;  
        }  
          
        String[] map = new String[10];  
        map[0] = "";  
        map[1] = "";  
        map[2] = "abc";  
        map[3] = "def";  
        map[4] = "ghi";  
        map[5] = "jkl";  
        map[6] = "mno";  
        map[7] = "pqrs";  
        map[8] = "tuv";  
        map[9] = "wxyz";  
          
        int[] number = new int[digits.length()];    //存储digits中每个字符在循环中的编号,初始为0  
          
        int k = digits.length()-1;  
        while(k>=0) {  
            k = digits.length()-1;  
            char[] charTemp = new char[digits.length()];  
            for(int i=0; i=0) {  
                if( number[k] < (map[digits.charAt(k)-'0'].length()-1) ) {  
                    number[k]++;  
                    break;  
                } else {  
                    number[k] = 0;  
                    k--;  
                }  
            }  
        }  
          
        return result;  
    }  

你可能感兴趣的:(leetcode)