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

leetcode Subsets

时间:2014-11-18 06:59:23      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:des   blog   io   ar   os   sp   java   for   div   

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],
  []
]
1,解法:对于数组中的每一个值,都添加到原来的list中去。
2, arrsys本身的sort函数,满足题目中non-descending的要求
public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
		if (S == null || S.length == 0) {
			return result;
		}
		Arrays.sort(S);
		result.add(new ArrayList<Integer>());

		for (int i = 0; i < S.length; i++) {
			int lengt = result.size();
			for (int j = 0; j < lengt; j++) {
				ArrayList<Integer> ad = new ArrayList<Integer>(result.get(j));
				ad.add(S[i]);
				result.add(ad);
			}
		}
		return result;
    }
}

  

leetcode Subsets

标签:des   blog   io   ar   os   sp   java   for   div   

原文地址:http://www.cnblogs.com/lilyfindjobs/p/4104823.html

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