Problem
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Solution (Java)
class Solution {
public List<List<Integer>> permute(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
List<List<Integer>> finalResult = new ArrayList<>();
permuteRecur(nums, finalResult, new ArrayList<>(), new boolean[nums.length]);
return finalResult;
}
private void permuteRecur(
int[] nums, List<List<Integer>> finalResult, List<Integer> currResult, boolean[] used) {
if (currResult.size() == nums.length) {
finalResult.add(new ArrayList<>(currResult));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
currResult.add(nums[i]);
used[i] = true;
permuteRecur(nums, finalResult, currResult, used);
used[i] = false;
currResult.remove(currResult.size() - 1);
}
}
}
Solution (Javascript)
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
var res = [];
dfs(res, [], nums);
return res;
};
var dfs = function (res, arr, nums) {
var len = nums.length;
var tmp1 = null;
var tmp2 = null;
if (!len) return res.push(arr);
for (var i = 0; i < len; i++) {
tmp1 = Array.from(arr);
tmp1.push(nums[i]);
tmp2 = Array.from(nums);
tmp2.splice(i, 1);
dfs(res, tmp1, tmp2);
}
};
Explain:
nope.
Complexity:
- Time complexity : O(n!).
- Space complexity :