Generate 10-digit number using a phone keypad

后端 未结 12 949
遥遥无期
遥遥无期 2020-12-13 14:12

Given a phone keypad as shown below:

1 2 3
4 5 6
7 8 9
  0

How many different 10-digit numbers can be formed starting from 1? The constrain

12条回答
  •  半阙折子戏
    2020-12-13 15:02

    //Both the iterative and recursive with memorize shows count as 1424 for 10 digit numbers starting with 1. 
    int[][] b = {{4,6},{6,8},{7,9},{4,8},{0,3,9},{},{1,7,0},{2,6},{1,3},{2,4}};
    public int countIterative(int digit, int length) {
        int[][] matrix = new int[length][10];
        for(int dig =0; dig <=9; dig++){
              matrix[0][dig] = 1;
        }
        for(int len = 1; len < length; len++){
            for(int dig =0; dig <=9; dig++){
              int sum = 0;
              for(int i : b[dig]){
                sum += matrix[len-1][i];
              }
              matrix[len][dig] = sum;
            }
        }
        return matrix[length-1][digit];
    }
    
    public int count(int index, int length, int[][] matrix ){
        int sum = 0;
        if(matrix[length-1][index] > 0){
            System.out.println("getting value from memoize:"+index + "length:"+ length);
            return matrix[length-1][index];
        }
        if( length == 1){
            return 1;
        }
        for(int i: b[index] )  {
             sum += count(i, length-1,matrix);
        }
        matrix[length-1][index] = sum;
        return sum;
    }
    

提交回复
热议问题