帮助完成排列类
我创建了一个类,用于用树计算整数的排列:
public class Permut {
ArrayList<Integer> list = new ArrayList<Integer>();
public static void main(String args[])
{
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(1);
t.add(2);
t.add(3);
Permut permutation = new Permut();
permutation.permutation(t);
}
public ArrayList<List> permutation(ArrayList<Integer> array)
{
Node node = new Node(); //root
node.data = -1;
node.depth = 1;
Node parent = node;
permut(parent,array,node.depth);
return null;
}
private void permut(Node parent, ArrayList<Integer> array, int i) {
// TODO Auto-generated method stub
ArrayList<Integer> noNumbers = new ArrayList<Integer>();
for (Integer in : array) {
if(!noNumbers.contains(in) || !parent.noList.contains(in)|| i<array.size())
{
Node no = new Node();
no.data = in;
no.parent = parent;
no.depth = i+1;
no.noList.add(in);
noNumbers.add(in);
permut(no,array,no.depth);
}
}
}
}
我的程序还有一个节点类,每个节点都有数据、父节点、深度,还有一个 nList,保存其父节点和祖节点的所有数据…… 我想通过读取从根到每个叶子的数据来进行排列。但是这段代码会导致 java.lang.StackOverflowError 我怎样
for (Integer in : array) {
才能完成我的代码?请您指导一下吗?谢谢
I have created a class for calculating the permutation of integer numbers with tree:
public class Permut {
ArrayList<Integer> list = new ArrayList<Integer>();
public static void main(String args[])
{
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(1);
t.add(2);
t.add(3);
Permut permutation = new Permut();
permutation.permutation(t);
}
public ArrayList<List> permutation(ArrayList<Integer> array)
{
Node node = new Node(); //root
node.data = -1;
node.depth = 1;
Node parent = node;
permut(parent,array,node.depth);
return null;
}
private void permut(Node parent, ArrayList<Integer> array, int i) {
// TODO Auto-generated method stub
ArrayList<Integer> noNumbers = new ArrayList<Integer>();
for (Integer in : array) {
if(!noNumbers.contains(in) || !parent.noList.contains(in)|| i<array.size())
{
Node no = new Node();
no.data = in;
no.parent = parent;
no.depth = i+1;
no.noList.add(in);
noNumbers.add(in);
permut(no,array,no.depth);
}
}
}
}
My program also has a node class, each node has data, parent, depth and also a nList that keeps all of the datas of its parent and grandparent and …
I want to have permutation by reading the datas from the root to each leaf. But this code cause java.lang.StackOverflowError
At the line
for (Integer in : array) {
how can I complete my code? Would you please guid me? thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于 noNumbers 是新初始化的 ArrayList,因此出现堆栈溢出。创建它后,您立即检查它是否不包含“in”。
这将永远运行,因为每个新级别的 noNumbers 在其第一次迭代中不会包含任何内容。
You are getting a stack overflow because noNumbers is a newly initialized ArrayList. Right after you create it you check to see if it doesn't contain "in"
This will run forever, because each new level's noNumbers will not contain anything on its first iteration.