我正在尝试从数字中获取所有排列。我作为numList和tmpList传递,在每个fn调用中,第一个元素从当前列表中提取并添加到tmpList中,直到我有了numlist为空的基本情况。我希望一旦到达.. numList为空,tmpList为[1,2,3],它应该又回到numlist [1,2,3],tmpList为空的旧函数,但不是。仅获得[[1,2,3]]作为输出。.我缺少什么?下面的代码
class Solution {
List<List<Integer>> output= new ArrayList<List<Integer>>();
public List<List<Integer>> permute(int[] nums) {
List<Integer> numList= new ArrayList<>();
for(int val:nums) {
numList.add(val);
}
List<Integer> tmpList= new ArrayList<>();
helper(numList,tmpList);
return output;
}
private void helper(List<Integer> numList, List<Integer> tmpList) {
System.out.println("After recursion");
if(numList.isEmpty()) {
output.add(tmpList);
return;
}
for(int i=0;i<numList.size();i++) {
tmpList.add(numList.get(i));
numList.remove(i);
helper(numList,tmpList);
}
}
}
当您使用numlist.remove(i)
时,numlist的大小将改变。因此,请使用常量变量代替for循环中的numlist.size()
。我认为此代码可能有效。
class Solution
{
List<List<Integer>> output= new ArrayList<List<Integer>>();
int numsize; //the constant variable
public List<List<Integer>> permute(int[] nums) {
numsize=nums.length;
List<Integer> numList= new ArrayList<>();
for(int val:nums)
{
numList.add(val);
}
List<Integer> tmpList= new ArrayList<>();
helper(numList,tmpList);
return output;
}
private void helper(List<Integer> numList, List<Integer> tmpList)
{
System.out.println("After recursion");
if(numList.isEmpty())
{
output.add(tmpList);
return;
}
for(int i=0;i<numsize;i++) //using constant variable
{
tmpList.add(numList.get(i));
numList.remove(i);
helper(numList,tmpList);
}
}
}
因为您已声明将permute()的返回声明为
List <List<Integer>>
因此您得到[[1234]]
class Solution {
List<Integer> output= new ArrayList<Integer>();
public List<Integer> permute(int[] nums) {
List<Integer> numList= new ArrayList<>();
for(int val:nums)
{
numList.add(val);
}
List<Integer> tmpList= new ArrayList<>();
helper(numList,tmpList);
return output;
}
private void helper(List<Integer> numList, List<Integer> tmpList)
{
System.out.println("After recursion");
if(numList.isEmpty())
{
for (Integer I:tmpList) output.add(I);
return;
}
for(int i=0;i<numList.size();i++)
{
tmpList.add(numList.get(i));
numList.remove(i);
helper(numList,tmpList);
}
}
}
您将获得[1,2,3]
这里的主要问题是不变性。好在这里解释:https://www.youtube.com/watch?v=IPWmrjE1_MU