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<ArrayList<Integer>> permute(ArrayList<Integer> nums) { // write your code here ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(nums == null || nums.size() == 0) return result; ArrayList<Integer> line = new ArrayList<Integer>(); boolean[] visited = new boolean[nums.size()]; helper(result, line, visited, nums); return result; } public void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> line, boolean[] visited, ArrayList<Integer> nums){ if(line.size() == nums.size()){ result.add(new ArrayList<Integer>(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; } }
时间: 2024-10-08 06:00:18