我在编写算法来计算树中独立集合的数量时遇到了困难。 (一个独立的组为其中任意两个节点之间有没有边。)独立集合的算法总数总是减1
这里是我的ListNode java类:
1public class ListNode
2{
3 private Object data;
4 private ListNode next;
5
6 public ListNode(Object data, ListNode next)
7 {
8 this.data = data;
9 this.next = next;
10 }
11
12 public Object getData() {return data;}
13 public ListNode getNext(){return next;}
14 public void setNext(ListNode n){next = n;}
15 public void setData(Object d){data = d;}
16 public boolean search(ListNode l, Object o)
17 {
18 while (l != null){
19 if (l.getData().equals(o))
20 return true;
21 l = l.getNext();
22 }
23 return false;
24 }
25 public static ListNode rev(ListNode curr)
26 {
27 ListNode rev = null;
28 while (curr != null){
29 rev = new ListNode(curr.getData(), rev);
30 curr = curr.getNext();
31 }
32 return rev;}}
而且我对树节点java类:
1public class TreeNode
2{ ListNode children = null;
3 public void addChild(TreeNode t)
4 {
5 if (children == null)
6 children = new ListNode(t, null);
7 else{
8 ListNode curr = children;
9 while (curr.getNext() != null)
10 curr = curr.getNext();
11 curr.setNext(new ListNode(t, null));
12 }}
13 public void setChildren(ListNode t){this.children = t;}
14 public int numStableSet()
15 {
16
17 if (children == null || children.getNext() == null)
18 return 2;
19 else{
20 int count = 2;
21 setChildren(children.getNext());
22 count *= numStableSet();
23 return count;
24 }
25 }
方法numStableSet是我需要一些编码帮助的地方。如现在设置,它打印出1比正确的答案少。我还没有想出每个节点本身可能是树的情况。
帮助赞赏
也许很明显的答案,但不能只是返回/输出任何你得到'+ 1'? – Annabelle
@Link Ya,我考虑过这个问题,但我不确定把+1放在哪里,因为算法需要是递归的。将+1放在错误的地方会导致超出正确的答案。 –
我怀疑你可以/应该把它放在最终结果即将返回的地方吗? – Annabelle