您的位置:首页 > 其它

Subsets

2015-06-17 15:06 246 查看
Given a set of distinct integers, nums, 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 nums =
[1,2,3]
,
a solution is:

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

这个题目和上一篇的combinations思路非常接近,相当于那里的k从0到n罢了。注意要将给的数组排个序才能用之前的那种方法。

代码如下:

public class Solution {

int[] S = {};
int len = 0;
List<List<Integer>> ans = new ArrayList<List<Integer>>();
//定义为成员变量,方便在不同的函数之间都能使用,不用当做参数,传来传去的。
public List<List<Integer>> subsets(int[] nums) {
this.S = nums;
this.len = nums.length;
Arrays.sort(S);

for (int i = 0; i <= len; i++) {
dfs(new ArrayList<Integer>(), 0, i);
}
return ans;
}

public void dfs(List<Integer> list, int from, int tar) {
if (list.size() == tar) {
List<Integer> res = new ArrayList<Integer>(list);
ans.add(res);
} else {
for (int i = from; i < len; i++) {
list.add(S[i]);
backTracking(list, i + 1, tar);
list.remove(list.size()-1);
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: