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], [] ]
使用DFS进行遍历。public void getSets(int[] S, int start, int end, List<List<Integer>> list, List<Integer> subList) { list.add(subList); for (int i = start; i < end; i++) { List<Integer> newSubList = new ArrayList<Integer>(subList); newSubList.add(S[i]); getSets(S, i + 1, end, list, newSubList); } } public List<List<Integer>> subsets(int[] S) { Arrays.sort(S); List<List<Integer>> list = new ArrayList<List<Integer>>(); List<Integer> subList = new ArrayList<Integer>(); getSets(S, 0, S.length, list, subList); return list; }
利用n和n-1之间的关系,n的集合等于n-1的集合加上n-1集合的每一个元素加上S[n]。// public List<List<Integer>> subsets(int[] S) { // Arrays.sort(S); // List<List<Integer>> list = new ArrayList<List<Integer>>(); // List<Integer> subList0 = new ArrayList<Integer>(); // list.add(subList0); // int len = S.length; // if (len == 0) { // return list; // } // List<Integer> subList1 = new ArrayList<Integer>(); // subList1.add(S[0]); // list.add(subList1); // if (len == 1) { // return list; // } // for (int i = 1; i < len; i++) { // int value = S[i]; // int size = list.size(); // for (int j = 0 ; j < size; j++) { // List<Integer> subList = list.get(j); // List<Integer> newSubList = new ArrayList<Integer>(subList); // newSubList.add(value); // list.add(newSubList); // } // } // return list; // }
Light OJ 1026 Critical Links 求桥,布布扣,bubuko.com
Light OJ 1026 Critical Links 求桥
原文地址:http://blog.csdn.net/u011686226/article/details/29187747