Friday, January 9, 2015

LeetCode 78: Subsets

Given a set of distinct integers, S, return all possible subsets.
Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
public class Solution {
    private List<List<Integer>> result;
    private List<Integer> ret;
    
    public List<List<Integer>> subsets(int[] S) {
        // Backtracking problem
        // Firstly, sort S array
        result = new LinkedList<>();
        ret = new LinkedList<>();
        result.add(ret); // Don't miss NULL set.
        
        int n = S.length;
        
        if (n == 0)
            return result;
            
        Arrays.sort(S);
            
        backTracking(S, 0);
        
        return result;
    }
    
    private void backTracking(int[] S, int cnt)
    {
        if (cnt == S.length)
            return;
        else
        {
            for (int i = cnt; i < S.length; i++)
            {
                ret.add(S[i]);
                
                List<Integer> copyRet = new LinkedList<>(ret);
                result.add(copyRet);
                
                backTracking(S, i+1);
                ret.remove(ret.size()-1);
            }
        }
    }
}

No comments:

Post a Comment