Leetcode78. Subsets

沿着之前的思路,有点僵硬,想着加几一个循环:

 1 class Solution {
 2     public List<List<Integer>> subsets(int[] nums) {
 3         List<List<Integer>> ans = new ArrayList<>();
 4         ans.add(new ArrayList<>());
 5         if(nums==null||nums.length==0) return ans;
 6         for(int i=1;i<=nums.length;i++){
 7             helper(ans,new ArrayList<>(),nums,i,0);
 8         }
 9         return ans;
10     }
11     private void helper(List<List<Integer>> ans,List<Integer> tempList,int[] nums,int length,int start){
12         if(tempList.size()==length) ans.add(new ArrayList<>(tempList));
13         else{
14             for(int i=start;i<nums.length;i++){
15                 // if(!tempList.contains(nums[i])) 
16                 tempList.add(nums[i]);
17                 helper(ans,tempList,nums,length,i+1);
18                 tempList.remove(tempList.size()-1);
19             }
20         }
21     }
22 }

4ms,5.4%极慢。

然后参考39题的那个discuss。

 1 class Solution {
 2     public List<List<Integer>> subsets(int[] nums) {
 3         List<List<Integer>> ans = new ArrayList<>();
 4         if(nums==null||nums.length==0) return ans;
 5         helper(ans,new ArrayList<>(),nums,0);
 6         return ans;
 7     }
 8     private void helper(List<List<Integer>> ans,List<Integer> tempList,int[] nums,int start){
 9         ans.add(new ArrayList<>(tempList));
10         for(int i=start;i<nums.length;i++){
11             tempList.add(nums[i]);
12             helper(ans,tempList,nums,i+1);
13             tempList.remove(tempList.size()-1);
14         }
15     }
16 }

1ms 100%。

可以了。

posted @ 2018-12-27 17:05  大胖子球花  阅读(127)  评论(0)    收藏  举报