打印列表的所有子集

时间:2015-03-27 01:05:41

标签: java recursion nodes

recursiveSum(Node currentNode) {
      if (currentNode == null){
            System.out.println("done " ); 
      }else{ recursiveSum(currentNode.next); 
        } 
}

继承节点类和递归方法。我已经尝试了所有可能想到的东西来返回所有可能的子集...如果我将数字{`1,2,3}添加到列表中,递归方法应该打印:{1,2,3} {1 ,3} {1,2} {1} {1,3} {2} {3} {0}

 private static class Node {
    Node next;
    int number;

    public Node(int numberValue) {
        next = null;
        number = numberValue;
    }

    public int getNumber() {
        return number;
    }

    public void setData(int numberValue) {
        number = numberValue;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node nextValue) {
        next = nextValue;
    }
}

1 个答案:

答案 0 :(得分:0)

正如笔记一样,递归不是数据结构,它是一种迭代技术。假设您的链接列表如下所示,并且您正在使用包含LinkedList个对象的Java Node对象,则通过它进行递归相对简单。

(node 1)->(node 2)->(node N)->NULL

递归所需的只是一个基本案例,也是获取链表中下一个节点的方法。

public void walk_list(LinkedList<Node> list){

    //the poll method retrieves and removes the head of the list
    //if the list is empty, it returns null
    Node n = list.poll();

    //Base case - list is empty
    if(n == null){
        return;
    }

    System.out.println(n.toString());
    walk_list(list);
}

现在,如果您的LinkedList看起来像这样

(node 1)->{ (node 2), (node 3) }
(node 2)->{ (node 4) }
(node 3)->{ (node 5), (node 6) }
(node 6)->{ (node 1) }

你有一个循环图。搜索此图表有几种方法,最简单的方法是广度优先搜索或深度优先搜索。两者都可以递归,就像给定的例子一样。您所要做的就是保留一些列表(队列,数组列表等)以了解接下来要搜索的内容,并且图中的每个节点都应该具有visited属性,该属性是设置的布尔值当你得到那个节点的孩子。

在澄清问题后,请查看此question and answer。你想做一个递归的排列。所以你需要的只是SetInteger个对象。