78. Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note:The solution set must not contain duplicate subsets.

For example,
If nums =[1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

思路:大绝招

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        Arrays.sort(nums);
        traceback(list,temp,nums,0);
        return list;
    }

    public void traceback(List<List<Integer>> list, List<Integer> temp, int[] nums, int start){
        list.add(new ArrayList<Integer>(temp));
        for (int i=start;i<nums.length;i++){
            temp.add(nums[i]);
            traceback(list,temp,nums,i+1);
            temp.remove(temp.size()-1);
        }
        return;
    }
}

results matching ""

    No results matching ""