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],
[]
]
解法
采用递归的方法,直到每一个list的最后一个数为数组中最大的数,返回。
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> subset = new ArrayList<Integer>();
if(nums == null || nums.length == 0 ) {
return results;
}
Arrays.sort(nums);
helper(results, subset, nums, 0);
return results;
}
private void helper(List<List<Integer>> results,
List<Integer> subset,
int[] nums,
int startIndex) {
// 注意要new新的对象,不然只是对象的引用,对象发生新的变化时,results中的数会跟着变
results.add(new ArrayList<Integer>(subset));
for (; startIndex < nums.length; startIndex++) {
subset.add(nums[startIndex]);
helper(results, subset, nums, startIndex + 1);
subset.remove(subset.size() - 1);
}
}
}
本文介绍了一种使用递归实现的子集生成算法,该算法能够针对一组不重复的整数生成所有可能的子集组合,并确保结果中不含重复的子集。
1503

被折叠的 条评论
为什么被折叠?



