Simple java recursion solution,1ms


  • -2
    D
    public class Solution {
    
    private String[] maps = new String[ 10 ];
    
    private void make() {
    	maps[ 2 ] = new String( "abc" );
    	maps[ 3 ] = new String( "def" );
    	maps[ 4 ] = new String( "ghi" );
    	maps[ 5 ] = new String( "jkl" );
    	maps[ 6 ] = new String( "mno" );
    	maps[ 7 ] = new String( "pqrs" );
    	maps[ 8 ] = new String( "tuv" );
    	maps[ 9 ] = new String( "wxyz" );
    }
    
    public List<String> letterCombinations( String digits ) {
    	make();
    	List<String> ret = new ArrayList<String>();
    	if( digits.length() < 1 )
    		return ret;
    	go( ret, digits, "", 0 );
    	return ret;
    }
    
    private void go( List<String> ret, String digits, String str, int pos ) {
    	if( pos == digits.length() - 1 ) {
    		String s = maps[ digits.charAt( pos ) - '0' ];
    		for( int i = 0; i < s.length(); i++ ) {
    			ret.add( str + s.charAt( i ) );
    		}
    	} else {
    		String s = maps[ digits.charAt( pos ) - '0' ];
    		for( int i = 0; i < s.length(); i++ ) {
    			go( ret, digits, str + s.charAt( i ) + "", pos + 1 );
    		}
    	}
    }
    

    }


Log in to reply
 

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