How can I print out all possible letter combinations a given phone number can represent?

前端 未结 30 2218
逝去的感伤
逝去的感伤 2020-12-22 18:01

I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations

30条回答
  •  一向
    一向 (楼主)
    2020-12-22 18:45

    Here is the working code for the same.. its a recursion on each step checking possibility of each combinations on occurrence of same digit in a series....I am not sure if there is any better solution then this from complexity point of view.....

    Please let me know for any issues....

    import java.util.ArrayList;
    
    
    public class phonenumbers {
    
        /**
         * @param args
         */
        public static String mappings[][] = {
            {"0"}, {"1"}, {"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"},
            {"J", "K", "L"}, {"M", "N", "O"}, {"P", "Q", "R", "S"}, 
            {"T", "U", "V"}, {"W", "X", "Y", "Z"}
        };
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            String phone = "3333456789";
            ArrayList list= generateAllnums(phone,"",0);
        }
    
        private static ArrayList generateAllnums(String phone,String sofar,int j) {
            // TODO Auto-generated method stub
    
            //System.out.println(phone);
            if(phone.isEmpty()){
                System.out.println(sofar);
                for(int k1=0;k1 list2= generateAllnums(phone.substring(p+1), sofar+phone.charAt(p)+ " ", 0);
                ArrayList list3= generateAllnums(phone.substring(p+1), sofar+phone.charAt(p), 0);
    
            }
            else{
                ArrayList list1= generateAllnums(phone.substring(1), sofar+phone.charAt(0), 0);
            }
            return null;
    
        }
    
    }
    

提交回复
热议问题