Subsets

来源:互联网 发布:netstat -an 看端口号 编辑:程序博客网 时间:2024/06/07 00:18

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],  []]
 Java代码:

public class Solution {   public List<List<Integer>> subsets(int[] S) {List<List<Integer>> result = new ArrayList<>();Arrays.sort(S);int len = S.length;for (int i = 1; i <= len; i++) {result.addAll(combineUTL(S, 0, len - 1, i));}result.add(0,new ArrayList<Integer>());return result;}public List<List<Integer>> combineUTL(int[] S, int start, int end,int k) {List<List<Integer>> list = new ArrayList<List<Integer>>();if (start > end || k == 0 || end - start + 1 < k)return null;if (end - start + 1 == k) {List<Integer> list_over = new ArrayList<>();for (int i = start; i <= end; i++)list_over.add(S[i]);list.add(list_over);} else {List<List<Integer>> list_1 = combineUTL(S, start + 1, end, k - 1);if (null != list_1) {for (List<Integer> list_tmp : list_1) {list_tmp.add(0, S[start]);}} else {if (k - 1 == 0) {list_1 = new ArrayList<List<Integer>>();List<Integer> list_tmp = new ArrayList<>();list_tmp.add(S[start]);list_1.add(list_tmp);}}List<List<Integer>> list_2 = combineUTL(S, start + 1, end, k);if (null != list_1)list.addAll(list_1);if (null != list_2)list.addAll(list_2);}return list;}}


0 0
原创粉丝点击