Google Foobar号码站

编程入门 行业动态 更新时间:2024-10-14 18:14:28
本文介绍了Google Foobar号码站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试解决Google foobar的挑战,但我坚持如何更改此设置以使用递归.任何指针都会有所帮助

Im trying to solve a google foobar challenge but I am stuck on how to change this to use recursion. any pointers would be helpful

public static int[] answer(int[] l, int t) { // convert the array into a list List<Integer> list = new ArrayList<>(); for (int i : l) { list.add(i); } for (int i = 0; i < list.size(); i++) { Integer n = list.get(i); if (i >= 1) { Integer nMinus1 = list.get(i - 1); Integer nMinus2; Integer nMinus3; Integer nMinus4; Integer nMinus5; Integer nMinus6; if (n + nMinus1 == t) { // done return new int[]{i - 1, i}; } else if (i >= 2) { nMinus2 = list.get(i - 2); if (n + nMinus1 + nMinus2 == t) { // done return new int[]{i - 2, i}; } else if (i >= 3) { nMinus3 = list.get(i - 3); if (n + nMinus1 + nMinus2 + nMinus3 == t) { // done return new int[]{i - 3, i}; } else if (i >= 4) { nMinus4 = list.get(i - 4); if (n + nMinus1 + nMinus2 + nMinus3 + nMinus4 == t) { // done return new int[]{i - 4, i}; } else if (i >= 5) { nMinus5 = list.get(i - 5); if (n + nMinus1 + nMinus2 + nMinus3 + nMinus4 + nMinus5 == t) { // done return new int[]{i - 5, i}; } else if (i >= 6) { nMinus6 = list.get(i - 6); if (n + nMinus1 + nMinus2 + nMinus3 + nMinus4 + nMinus5 + nMinus6 == t) { // done return new int[]{i - 6, i}; } } } } } } } } return new int[]{-1, -1}; }

这是问题:

给定列表l为[4、3、5、7、8],键t为12,函数answer(l,t)将返回列表[0,2],因为列表l包含子项-list [4,3,5]从索引0开始到索引2,对于索引4 + 3 + 5 = 12,即使列表中的后面出现的序列较短(5 + 7),也是如此.另一方面,给定列表l为[1、2、3、4],键t为15,由于没有子列表,函数answer(l,t)将返回[-1,-1]列表l的总和可以等于给定的目标值t = 15.

Given the list l as [4, 3, 5, 7, 8] and the key t as 12, the function answer(l, t) would return the list [0, 2] because the list l contains the sub-list [4, 3, 5] starting at index 0 and ending at index 2, for which 4 + 3 + 5 = 12, even though there is a shorter sequence that happens later in the list (5 + 7). On the other hand, given the list l as [1, 2, 3, 4] and the key t as 15, the function answer(l, t) would return [-1, -1] because there is no sub-list of list l that can be summed up to the given target value t = 15.

推荐答案

您可能不需要arraylist.您可以在数组l上执行双循环.为什么要递归?

You probably don't need an arraylist. You could perform a double loop on the array l. Why do you want recursion?

您可以执行以下操作:

public static int[] answer(int[] l, int t) { int[] rets = {-1, -1}; int sum=0; for (int i=0; i<l.length; i++) { sum=0; for (int j=i; j<l.length; j++) { sum+=l[j]; if (sum > t) break; if (sum == t) { rets[0] = i; rets[1] = j; return rets; } } } return rets; }

更多推荐

Google Foobar号码站

本文发布于:2023-11-29 11:20:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646254.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:号码   Google   Foobar

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!