Friday, May 1, 2015

[LeetCode] Permutations

Permutations

Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].
Solution: The beauty of recursion!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        ArrayList<List<Integer>> list = new ArrayList<List<Integer>>();
        if (nums.length == 0) {
            return list;
        }
        if (nums.length == 1) {
            ArrayList<Integer> l = new ArrayList<Integer>();
            l.add(nums[0]);
            list.add(l);
            return list;
        }
        List<List<Integer>> li = permute(
                Arrays.copyOfRange(nums, 1, nums.length)
            );
        for (List<Integer> ll : li) {
            for (int i = 0; i <= ll.size(); i++) {
                ArrayList<Integer> l = new ArrayList<Integer>(ll);
                l.add(i, nums[0]);
                list.add(l);
            }
        }
        return list;
    }
}

No comments:

Post a Comment