首页 > 解决方案 > 如果相同,则将数组中的值相乘

问题描述

我想写一个遵循这个逻辑的递归方法:

假设如果数组是 [3, 3, 3, 3] 它将返回值 30,因为 trail[i] 的连续数字彼此相等。所以这里发生的是 3 + (3 * 2) + (3 * 3) + (3 * 4) = 30

另一个例子是 [2, 4, 3] 它将返回值 9

我希望这是有道理的

任何人都可以帮忙吗?

标签: java

解决方案


你可以试试这个方法

  int sum(int pos, int[] trail, int cnt) {
    if (pos >= trail.length) {   // when full array traversed
      return 0;
    }
    if (pos != 0 && trail[pos - 1] == trail[pos]) {         // if previous element is same 
      return (cnt + 1) * trail[pos] + sum(pos + 1, trail, cnt + 1);
    } else {                                                // first element or prev not same
      return trail[pos] + sum(pos + 1, trail, 1);
    }
  }

并以这种方式调用sum(0, trail, 0)


推荐阅读