Permutations

Given a collection of distinct numbers, return all possible permutations.

For example,

[1,2,3] have the following permutations:

  1. [
  2. [1,2,3],
  3. [1,3,2],
  4. [2,1,3],
  5. [2,3,1],
  6. [3,1,2],
  7. [3,2,1]
  8. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> permute(int[] nums) {
  3. List<List<Integer>> res = new ArrayList<>();
  4. if (nums.length == 0)
  5. return res;
  6. res.add(new ArrayList<Integer>(Arrays.asList(nums[0])));
  7. for (int i = 1; i< nums.length; i++) {
  8. List<List<Integer>> next = new ArrayList<>();
  9. for (int j = 0; j <= i; j++) {
  10. for (List<Integer> list : res) {
  11. // make a copy of existing perm
  12. List<Integer> copy = new ArrayList<>(list);
  13. copy.add(j, nums[i]);
  14. next.add(copy);
  15. }
  16. }
  17. res = next;
  18. }
  19. return res;
  20. }
  21. }