Algorithm to efficiently determine the [n][n] element in a matrix

前端 未结 6 451
半阙折子戏
半阙折子戏 2020-12-30 07:07

This is a question regarding a piece of coursework so would rather you didn\'t fully answer the question but rather give tips to improve the run time complexity of my curren

6条回答
  •  孤独总比滥情好
    2020-12-30 07:31

    Thanks to will's (first) answer, I had this idea:

    Consider that any positive solution comes only from the 1's along the x and y axes. Each of the recursive calls to f divides each component of the solution by 3, which means we can sum, combinatorially, how many ways each 1 features as a component of the solution, and consider it's "distance" (measured as how many calls of f it is from the target) as a negative power of 3.

    JavaScript code:

    function f(n){
    
      var result = 0;
    
      for (var d=n; d<2*n; d++){
    
        var temp = 0;
    
        for (var NE=0; NE<2*n-d; NE++){
    
          temp += choose(n,NE);
        }
    
        result += choose(d - 1,d - n) * temp / Math.pow(3,d);
      }
    
      return 2 * result;
     }
    
    function choose(n,k){
      if (k == 0 || n == k){
        return 1;
      }
      var product = n;
      for (var i=2; i<=k; i++){
        product *= (n + 1 - i) / i
      }
      return product;
    }
    

    Output:

    for (var i=1; i<8; i++){
      console.log("F(" + i + "," + i + ") = " + f(i));
    }
    
    F(1,1) = 0.6666666666666666
    F(2,2) = 0.8148148148148148
    F(3,3) = 0.8641975308641975
    F(4,4) = 0.8879743941472337
    F(5,5) = 0.9024030889600163
    F(6,6) = 0.9123609205913732
    F(7,7) = 0.9197747256986194
    

提交回复
热议问题