Euler project #18 approach

后端 未结 9 890
鱼传尺愫
鱼传尺愫 2020-11-30 22:23

I am looking into an Euler project. Specifically #18.
To sum up, the idea is to find the max path from a triangle:

   3
  7 4
 2 4 6  
8 5 9 3
<         


        
9条回答
  •  我在风中等你
    2020-11-30 22:58

    static int getTriangle() throws FileNotFoundException, IOException{
            File file = new File("/home/rakib/This Pc/programming/problem solving/ProjectEuler/src/projecteuler/euluer17.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String n;
            int i = 0;
            int [][] array = new int[15][15];
            while((n = br.readLine()) != null){
                String [] temp = n.split(" ");
                for(int j = 0; j < temp.length; j++){
                     array[i][j] = Integer.parseInt(temp[j]);         
                }
                 i++;
            }
    
    
        for(int j = array.length-2; j >= 0; j--){
            int []tempArray = new int [j+1];
               for(int k =0; k <= j; k++){
                   tempArray[k] = array[j][k] + Math.max(array[j+1][k], array[j+1][k+1]);
               }
               array[j] = tempArray;
        }
    
     return array[0][0];
    }
    

    i used bottom up approach to solve this problem. working from last two row. just add max value with path element.

提交回复
热议问题