和为定值的m个数

和为定值的m个数

np 问题(时间复杂度o(2**n))

 

 

 

code1:

暴力递归

解决 只有正数的情况

 1 class Solution {
 2     private List<List<Integer>> res = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> fourSum(int[] nums, int target) {
 4         boolean[] a = new boolean[nums.length];
 5         for(int i = 0;i <a.length-1;i++)
 6             a[i] = false;
 7         sum(nums,a,0,0,target);
 8         return res;
 9     }
10     private void sum(int[] nums,boolean[] a,int i,int has,int target){
11         if(i>a.length-1) return;
12         if(has + nums[i] == target){
13             a[i] = true;
14             
15             res.add(add_res(nums,a));
16             a[i] = false;
17         }
18         a[i] = true;
19         sum(nums,a,i+1,has+nums[i],target);
20         a[i] = false;
21         sum(nums,a,i+1,has,target);
22     }
23     private List<Integer> add_res (int[] nums,boolean[] a){
24         List<Integer> res = new ArrayList<Integer>();
25         for(int i = 0;i<a.length;i++)
26             if(a[i])
27                 res.add(nums[i]);
28         return res;
29     }
30 }

 

posted @ 2018-02-20 23:43  乐乐章  阅读(264)  评论(0编辑  收藏  举报