什么程序打印错误的reutls

时间:2017-09-01 17:58:20

标签: java recursion

我想做的是:

我有一个值列表,我想列出它们中的每三个。例如:

我有:

"one", "two", "three", "four", "five"

我想打印以下内容:

one two three
one two four
one four five
two three four
two three five
and so on

你明白了,我想要每三个值(不按顺序排序)

我做的是:

import java.util.*;

public class Solution {
    public static void main(String args[]) {
        String[] people = new String[] { "one", "two", "three", "four",
                "five" };
        Solution s = new Solution();
        s.solve(people, 3, new LinkedList<>(), 0);
    }

    public void solve(String[] people, int n, List<String> data, int i) {
        if (data.size() == n) {
            System.out.println(data.toString());

        } else if (i < people.length) {
            String value = people[i];
            solve(people, n, data, i + 1);
            data.add(value);
            solve(people, n, data, i + 1);
        }
    }
}

你可以运行它:

我的问题是打印出来了:

  

[五,四,五]

这显然是错误的,怎么能打印两个相同的值?在我的代码中,我添加了一次值,我不再添加它

你可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

  

怎么能打印两个相同的值?

原因在于您已将代码放入代码中:

else if (i < people.length) 

带您完成执行框架:

solve(people, n, data, i + 1); 

// (1) this recurses until i = 4(which is less than the length=5)
// for the next iteration the condition i<people.length wouldn't be satisfied

// (2) hence this is called
data.add(value);  // data now has "five"

// since when the previous recursion ended i=4 (callee)
solve(people, n, data, i + 1); 
// (3) this recurses again and finds the same condition of not being able to recurse more
// hence data gets value = "four"

使用i+1,它会旋转回(1)并打印&#34;五&#34;试。

PS :如果之后会发生什么,我会留给你弄清楚。

提示 :执行不会在这里结束。 提示++ :递归回溯。

答案 1 :(得分:0)

public void solve(String[] people, int n, List<String> data, int i) {
    if (data.size() == n) {
        System.out.println(data.toString());
        return;
    }

    if (i == people.length) {
        return;
    }

    data.add(people[i]);
    solve(people, n, data, i + 1);
    data.remove(people[i]);
    solve(people, n, data, i + 1);
}

输出

[one, two, three]
[one, two, four]
[one, two, five]
[one, three, four]
[one, three, five]
[one, four, five]
[two, three, four]
[two, three, five]
[two, four, five]
[three, four, five]