当前位置: 代码迷 >> J2SE >> java 递归计算结果保存在大局变量中.返回后结果丢失
  详细解决方案

java 递归计算结果保存在大局变量中.返回后结果丢失

热度:73   发布时间:2016-04-23 20:06:25.0
java 递归计算结果保存在全局变量中.返回后结果丢失
先贴代码:
package permute;

import java.util.ArrayList;
import java.util.List;

public class Solution {
public boolean used[];
public  List<List<Integer> > ans;                   //就是这个变量
public  List<Integer> tans ;
public  List<List<Integer> > permute(int[] num)
{
used=new boolean[num.length+1];
ans=new ArrayList<List<Integer>>();
tans=new ArrayList<Integer>() ;
for(int i=0;i<used.length;i++)
used[i]=false;
my_next_permute(0,num.length,num);
return ans;
}
public void my_next_permute(int pos,int n,int[] num)
{

if(pos==n)
{
ans.add(tans);                    //调试到这里没问题,ans=[ [1] ];
tans.clear();                       //清空临时变量
return ;                             //返回后ans=[ [ ] ]  ,,郁闷
}
for(int i=0;i<n;i++)
{
if(!used[i])
{
tans.add(new Integer(num[i]));                //到这里也没问题
used[i]=true;
my_next_permute(pos+1,n,num);       //递归调用
used[i]=false;
}
}
}
};

平时用c/c++用的比较多.对java不太熟.
问题在注释中说了.在递归中调试看的ans保存的值是正确的.但是返回后ans就被清空了.
麻烦谁可以说下原因和解决办法..谢
------解决思路----------------------
ans里面放的只是tans的引用
  相关解决方案