和為定值的m個數
阿新 • • 發佈:2018-02-21
pos col list spa num span int false code
和為定值的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 }
和為定值的m個數