How to improve integer partitioning with n,m,k

我们两清 提交于 2021-01-29 14:52:41

问题


my program counts the integer partitions of n, which have k distinct partition elements, each is smaller or equal to m. How can i improve the performance? I already cache immediate results.

public long q(int n, int m, int k){
  return q1(n,m,k,0,0,new HashMap());
}

private long q1(int n, int m, int k, int level, int last, Map<String, Long> cache){
  if(n <0){
    return 0;
  }
  if(level+1 ==k){
    if(n >m){
      return 0;
    } else {
      return 1;
    }
  }
  int first = (level == 0) ? 1 : last+1;

  long total = 0;

  for(int i = first; i<= Math.min(m, n/2); i++){
    last = i;

    if ( n - i > 0 && last < n-i) {
      String key = n-i+"_"+level+1+"_"+last;

      Long fetched = cache.get(key);

      if(fetched ==null){
        fetched = q1(n-i,m,k,level+1,last, cache);
        cache.put(key, fetched);
      }
      total += fetched;
    }
  return total;
}

来源:https://stackoverflow.com/questions/60347184/how-to-improve-integer-partitioning-with-n-m-k

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!