Java recursive, dfs, backtracking


  • 0
    Z
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ret = new LinkedList<>();
        if(nums == null || nums.length == 0)
            return ret;
    
        List<Integer> path = new ArrayList<>();
        helper(ret, path, nums);
    
        return ret;
    
    }
    
    void helper(List<List<Integer>> ret, List<Integer> path, int[] ns){
        if(ns.length == path.size()){
            ret.add(new ArrayList<>(path));
            return ;
        }
    
        for(int n: ns){
            if(!path.contains(n)){
                path.add(n);
                helper(ret,path, ns );
                path.remove(path.size() -1);
            }
        }
    }

  • 0
    J

    public IList<IList<int>> Permute(int[] nums)
    {
    IList<IList<int>> list = new List<IList<int>>();
    int count;
    list.Add(nums.ToList());
    IList<int> e;
    for (int i = nums.Length - 2; i >= 0; i--)
    {
    count = list.Count();
    for (int j = 0; j <count; j++)
    for (int k = 0; k < nums.Length - 1 - i; k++)
    {
    e = new List<int>(list[j]);
    e.RemoveAt(i);
    e.Insert(i + 1 + k, nums[i]);
    list.Add(e);
    }
    }

            return list;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.