简体   繁体   English

虽然循环逻辑存在缺陷

[英]While loop logic flaw

The problem is as below: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 问题如下:给定两个整数n和k,返回1 ... n中k个数的所有可能组合。

For example, If n = 4 and k = 2, a solution is: 例如,如果n = 4且k = 2,则解决方案是:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4]
]

My Solution is: 我的解决方案是:

public List<List<Integer>> combine(int n, int k) {
    Deque<List<Integer>> queue = new LinkedList<List<Integer>>();
    List<List<Integer>> result = new LinkedList<List<Integer>>();

    for (int i = 1; i <= n; i++) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(i);
        queue.add(list);
    }

    while (!queue.isEmpty()) {
        List<Integer> list = queue.pollFirst();
        if (list.size() == k)
            result.add(list);
        else {
            for (int i = list.get(list.size() - 1) + 1; i <= n; i++) {
                list.add(i);
                queue.addLast(list);
                list.remove(list.size() - 1);
            }
        }
    }
    return result;
}

However the while loop goes into a infinite loop. 然而while循环进入无限循环。 I have no idea what's wrong with the logic. 我不知道逻辑有什么问题。 I traced it for a couple of times but still can't find the logic flaw in this code. 我追踪了几次,但仍然无法找到此代码中的逻辑缺陷。

Your problem is that you are adding the same list instance to the queue multiple times, so when you write : 您的问题是您多次将相同的列表实例添加到队列中,因此在您编写时:

            list.add(i); // suppose that list had 1 element. After adding 1,
                         // it has two elements
            queue.addLast(list); // here you add the list with 2 elements to
                                 // the queue
            list.remove(list.size() - 1); // here you remove the added element
                                          // so the list you just added
                                          // to the queue has just 1 element

The list that you added to the queue remains with the original number of elements. 添加到队列的列表保留原始元素数。

You should create a new List instance before adding it to the queue : 您应该在将新实例添加到队列之前创建一个新的List实例:

            list.add(i);
            queue.addLast(new ArrayList<Integer>(list));
            list.remove(list.size() - 1);

以上while(!queue.isEmpty()){}始终为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM