标签:
Given a set of distinct integers, S, return all possible subsets.
Note:
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
思路:借助排列组合的想法,本题可以解释成分别从数组S中选择1个,2个,3个......n个元素的子序列有哪些,最后在结果中加上一个空集即可。为了实现有序,可以先对输入数组S进行排序,在代码中实现了快排。
代码如下:
1 List<List<Integer>> lists = new ArrayList<List<Integer>>(); 2 public List<List<Integer>> subsets(int[] S) { 3 fastSortingHelp(S, 0, S.length-1); 4 for(int i=1; i<=S.length; i++) { 5 subsetsHelper(S, i, 0, new ArrayList<Integer>()); 6 } 7 lists.add(new ArrayList<Integer>()); 8 return lists; 9 } 10 11 //快排代码 12 public void fastSortingHelp(int[] S, int start, int over) { 13 if(start >= over) 14 return; 15 int left = start; 16 int right = over; 17 int compare = start; 18 while(left < right) { 19 while(left < right && S[right] >= S[compare]) { 20 right--; 21 } 22 int tmp = S[right]; 23 S[right] = S[compare]; 24 S[compare] = tmp; 25 compare = right; 26 27 while(left < right && S[left] <= S[compare]) { 28 left++; 29 } 30 tmp = S[left]; 31 S[left] = S[compare]; 32 S[compare] = tmp; 33 compare = left; 34 } 35 fastSortingHelp(S, start, left-1); 36 fastSortingHelp(S, left+1, over); 37 } 38 39 //从数组S中,取得k个元素,这k个元素的下标都需>=start 40 public void subsetsHelper(int[] S, int k, int start, List<Integer> list) { 41 if(k == 1) { 42 for(int i=start; i<S.length; i++) { 43 list.add(new Integer(S[i])); 44 45 lists.add(new ArrayList<Integer>(list)); 46 list.remove(new Integer(S[i])); 47 } 48 } else { 49 for(int i=start; i<=S.length-k; i++) { 50 list.add(new Integer(S[i])); 51 subsetsHelper(S, k-1, i+1, list); 52 list.remove(new Integer(S[i])); 53 } 54 } 55 }
问题:如果出现重复元素怎么处理?
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4295588.html