码迷,mamicode.com
首页 > 其他好文 > 详细

Subsets

时间:2014-09-09 13:29:08      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   os   io   java   ar   strong   for   

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],
  []
]

答案

public class Solution {
    public void quickSort(int []S,int startIndex,int endIndex){
        if(startIndex>=endIndex){
            return;
        }
        int middleIndex=(startIndex+endIndex)/2;
        int p=S[middleIndex];
        S[middleIndex]=S[startIndex];
        S[startIndex]=p;
        int i=startIndex+1;
        int j=endIndex;
        for(;i<j;){
            while(i<j)
            {
                if(S[i]>=S[startIndex])
                {
                    break;
                }
                i++;
            }
            while(i<j)
            {
                if(S[j]<S[startIndex])
                {
                    break;
                }
                j--;
            }
            p=S[i];
            S[i]=S[j];
            S[j]=p;
        }
        if(S[i]>S[startIndex])
        {
            i--;
        }
        p=S[i];
        S[i]=S[startIndex];
        S[startIndex]=p;
        quickSort(S,startIndex,i-1);
        quickSort(S,i+1,endIndex);
        
    }
    public List<List<Integer>> subsets(int[] S) {
        List<List<Integer>> result=new LinkedList<List<Integer>>();
        List<List<Integer>> tmp=new LinkedList<List<Integer>>();
        List<Integer> p=new LinkedList<Integer>();
        result.add(p);
        if(S==null||S.length<=0)
        {
            return result;
        }
        int LEN=S.length;
        quickSort(S,0,LEN-1);
        for(int i=0;i<LEN;i++){
            tmp.clear();
            for(List<Integer>list:result){
                p=new LinkedList<Integer>();
                p.addAll(list);
                p.add(S[i]);
                tmp.add(p);
            }
            result.addAll(tmp);
        }
        return result;
    }
}


Subsets

标签:des   style   color   os   io   java   ar   strong   for   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39135597

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!