【问题标题】:Print all subsets of a list打印列表的所有子集
【发布时间】:2015-03-28 05:39:57
【问题描述】:
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;
    }
}

【问题讨论】:

  • 显示一小段代码,让您清楚自己在做什么。计算机科学一般不讲授 Stack Overflow,但会解决具体的技术问题或调试问题。
  • public static void recursiveSum(Node currentNode) { if (currentNode == null){ System.out.println("done" ); }else{ recursiveSum(currentNode.next); } }
  • 私有静态类 Node { Node next;整数;公共节点(int numberValue){下一个=空;数字=数字值; } public int getNumber() { 返回号码; } public void setData(int numberValue) { number = numberValue; } 公共节点 getNext() { 返回下一个; } public void setNext(Node nextValue) { next = nextValue; } }

标签: java recursion nodes


【解决方案1】:

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

(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 个对象。

【讨论】:

  • 是的,我是这个领域的新手,我有点不知所措。感谢您的见解(recusion 是一种迭代方法而不是数据结构)
  • 是的,不用担心。递归对我来说也绝非易事。您应该获取您在上面的 cmets 中发布的代码,并将它们作为代码块添加到您的问题中,以便它可读。看起来我给出的例子会让你非常接近你需要的地方。只需点击帖子上的编辑按钮,然后粘贴带有 4 个空格缩进的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多