首页 > 其他 > 详细

LeetCode Subsets

时间:2015-09-27 09:59:58      阅读:244      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/subsets/

这是一道NP题目,取res中现有list,每个list都加新的元素nums[i]然后再放回res中,同时保留原有list. 从[]开始一次加一个新元素。

Time O(2^n).

 AC Java:

 1 public class Solution {
 2     public List<List<Integer>> subsets(int[] nums) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         //Add [] to res.
 8         res.add(new ArrayList<Integer>());
 9         //non-descending order
10         Arrays.sort(nums);
11         for(int i = 0; i<nums.length; i++){
12             int size = res.size();
13             for(int j = 0; j< size; j++){
14                 //add new element to each element of res
15                 ArrayList<Integer> elem= new ArrayList<Integer>(res.get(j));
16                 elem.add(nums[i]);
17                 res.add(elem);
18             }
19         }
20         return res;
21     }
22 }

 

LeetCode Subsets

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4841881.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!