My recursion code


  • 0
    C
    public class Solution {
    public ArrayList<String> ret=new ArrayList<String>();
    public char[] numChars=null;
    
    public List<String> translateFromNumsToChar(char numChar){
        String[] result=null;
        switch (numChar){
            case '1':
                result=new String[]{"@"};
                break;
            case '2':
                result=new String[]{"a","b","c"};
                break;
            case '3':
                result=new String[]{"d","e","f"};
                break;
            case '4':
                result=new String[]{"g","h","i"};
                break;
            case '5':
                result=new String[]{"j","k","l"};
                break;
            case '6':
                result=new String[]{"m","n","o"};
                break;
            case '7':
                result=new String[]{"p","q","r","s"};
                break;
            case '8':
                result=new String[]{"v","t","u"};
                break;
            case '9':
                result=new String[]{"y","w","x","z"};
                break;
            case '*':
                result=new String[]{"+"};
                break;
            case '0':
                result=new String[]{" "};
                break;
            case '#':
                result=new String[]{""};
                break;
            default:
                result=new String[]{""};
                break;
        }
        return Arrays.asList(result);
    }
    
    public void getResult(String suffix,int index){
        List<String> strArray;
        strArray=translateFromNumsToChar(numChars[index]);
        if(index==0){
            for(int i=0;i<strArray.size();i++){
                ret.add(strArray.get(i)+suffix);
            }
            return;
        }else{
            index--;
            for(int i=0;i<strArray.size();i++){
                getResult(strArray.get(i)+suffix,index);
            }
        }
    }
    public List<String> letterCombinations(String digits) {
        // numChars=new char[]();
        numChars=digits.toCharArray();
        if(numChars.length==0) return ret;
        getResult("",numChars.length-1);
        return ret;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.