Thursday, January 8, 2015

LeetCode 46: 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].
public class Solution {
    private List<List<Integer>> result;

    public List<List<Integer>> permute(int[] num) {
        // BackTracking problem
        result = new LinkedList<>();
        
        backTrack(num, 0);
        
        return result;
    }
    
    private void backTrack(int[] num, int i)
    {
        if (i == num.length)
        {
            List<Integer> ret = new LinkedList<>();
            
            for (int number : num)
                ret.add(number);  
            
            result.add(ret);
            
            return;
        }
        else
        {
            for (int j = i; j < num.length; j++) // Note: j start from i
            {
                swap(num, i, j);
                backTrack(num, i+1);
                swap(num, i, j);
            }
        }
    }
    
    private void swap(int[] a, int i, int j)
    {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

No comments:

Post a Comment