如何使用递归迭代throguh数组中的所有可能组合?

时间:2017-08-17 14:39:44

标签: arrays recursion

我已经开始学习递归了,当我解决练习问题时,我发现它很混乱。

例如,如果我有一个排序顺序为[2,3,4,5,6,7,8,9]的数组,并且我希望迭代d跳转的所有可能组合,从第一个数字2开始直到结束数字{{ 1}}。

一些有效的跳跃是(对于d = 3次跳跃):

2→3→5→9

2→3→6-> 9

2→3→7-> 9

2→3→8-> 9

2→4-> 5→9

等等。

请告诉我如何处理这种递归问题。

2 个答案:

答案 0 :(得分:1)

此问题迅速减少:删除列表的两端。现在,您所要做的就是从剩余列表中选择 d-1 元素。在长度 n>的列表中查找 m 元素的所有组合m 很容易研究。你几乎可以肯定用你最喜欢的语言找到解决方案。

这种见解会让你感动吗?

答案 1 :(得分:0)

以下是计算可能的跃点的类的实现:

public class HopCalculator {

  private int[] input;

  public HopCalculator(int[] input) {
    this.input = input;
  }

输入数组是在施工时间内给出的。现在我们可以查询不同长度(跳数)的不同路由。 输出是包含可能路由的Set。 每个路由都是一个数组列表,其中包含它经过的数字。

  public Set<ArrayList<Integer>> findPossibleHops(int d) {
    Set<ArrayList<Integer>> options = new HashSet<>();
    ArrayList<Integer> option = new ArrayList<>();
    option.add(input[0]);

    findPossibleHopsRecursive(options, option, d-1, 1, input.length-2);
    return options;
  }

  private void findPossibleHopsRecursive(Set<ArrayList<Integer>> options, ArrayList<Integer> option, int d, int begin, int end) {
    if (d==0) {
        option.add(input[end+1]);
        options.add(option);
    }
    else {
        if (end - begin + 1 == d) {
            option.add(input[begin]);
            findPossibleHopsRecursive(options, option, d - 1, begin + 1, end);
        } else {
            ArrayList<Integer> option1 = new ArrayList<>();
            option1.addAll(option);
            option1.add(input[begin]);
            findPossibleHopsRecursive(options, option1, d - 1, begin + 1, end);

            ArrayList<Integer> option2 = new ArrayList<>();
            option2.addAll(option);
            findPossibleHopsRecursive(options, option2, d, begin + 1, end);
        }
    }
  }
}