Given a list of numbers, return all possible permutations.
Example
For nums = [1,2,3]
, the permutations are:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
Challenge
Do it without recursion.
class Solution { /** * @param nums: A list of integers. * @return: A list of permutations. */ public ArrayList> permute(ArrayList nums) { // write your code here ArrayList > result = new ArrayList >(); if(nums == null || nums.size() == 0) return result; ArrayList line = new ArrayList (); boolean[] visited = new boolean[nums.size()]; helper(result, line, visited, nums); return result; } public void helper(ArrayList > result, ArrayList line, boolean[] visited, ArrayList nums){ if(line.size() == nums.size()){ result.add(new ArrayList (line)); return; } for(int i = 0; i < nums.size(); i++){ if(!visited[i]){ line.add(nums.get(i)); visited[i] = true; helper(result, line, visited, nums); line.remove(line.size() - 1); visited[i] = false; } } return; } }