Java backtracking method, is it not a good idea to turn array to arraylist?


  • 0
    N

    my idea is similar to other backtracking method, but I convert the array to arraylist. When I try to do this in one line code: List<Integer> n = new ArrayList<Integer>(Arrays.asList(nums)) it gives out an error with no constructor. So LC thinks that it is not a good idea to turn array to a list?

        public class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            ArrayList<Integer> n = new ArrayList<Integer>();
            for(int num : nums)
            {
                n.add(num);
            }
            helper(res, new ArrayList<Integer>(),n);
            return res;
        }
        private void helper(List<List<Integer>> res, List<Integer> a, List<Integer> n )
        {
            
            if(n.size()==0)
            {
                res.add(a);
                return;
            }
            int len = n.size();
            for(int i=0; i< len; i++)
            {
                List<Integer> tmp = new ArrayList<Integer>(a);
                List<Integer> tmp_n = new ArrayList<Integer>(n);
                tmp.add(tmp_n.get(i));
                tmp_n.remove(i);
                helper(res,tmp,tmp_n);
            }
        }
    }

Log in to reply
 

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