List类的添加方法

时间:2019-11-13 21:24:43

标签: java xcode algorithm

我编写了以下代码来生成给定整数的排列

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

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length == 0){
            return result;
        }
        boolean[] visited = new boolean[nums.length];
        List current = new ArrayList<Integer>();
        permute_recursive(visited, nums, current, result);
        return result;


    }
    public void permute_recursive(boolean[] visited, int[] nums, List<Integer> current, 
List<List<Integer>> result){
        if(current.size() == nums.length){
            result.add(new ArrayList<Integer>(current));
            return;
        }
        for(int i = 0; i < nums.length; i++){
            if(visited[i]){
                continue;
            }
            visited[i] = true;
            current.add(nums[i]);
            permute_recursive(visited, nums, current, result);
            visited[i] = false;
            //do not want the next round to start with nums[i], but we just added it, so we need to 
remove it.
            current.remove(current.size() - 1);


        }
    }
}

问题是当我直接执行result.add(current)时,它只会向我返回一个空数组列表,我不知道为什么。

根据要求,我的主要方法是

public class test {
    public static void main(String[] args) {
        int[] test = new int[]{1,2,3};
    System.out.print(Solution.permute(test));
    }
}

这有什么关系?

0 个答案:

没有答案