|
| 1 | +packagemedium; |
| 2 | +importjava.util.*; |
| 3 | + |
| 4 | +importutils.CommonUtils; |
| 5 | + |
| 6 | +publicclassCombinationSumIV { |
| 7 | +//since this question doesn't require to return all the combination result, instead, it just wants one number, we could use DP |
| 8 | +//the idea is similar to Climbing Stairs. |
| 9 | +//adopted this solution: https://discuss.leetcode.com/topic/52186/my-3ms-java-dp-solution |
| 10 | +publicintcombinationSum4(int[]nums,inttarget){ |
| 11 | +Arrays.sort(nums); |
| 12 | +int[]result =newint[target+1]; |
| 13 | +for(inti =1;i <result.length;i++){ |
| 14 | +for(intn :nums){ |
| 15 | +if(n >target)break; |
| 16 | +elseif(n ==target)result[i] ++; |
| 17 | +elseresult[i] +=result[i-n]; |
| 18 | + } |
| 19 | + } |
| 20 | +returnresult[target]; |
| 21 | + } |
| 22 | + |
| 23 | +//this normal backtracking recursive solution will end up in TLE. |
| 24 | +publicList<List<Integer>>combinationSum4_printout(int[]nums,inttarget) { |
| 25 | +List<List<Integer>>result =newArrayList(); |
| 26 | +Arrays.sort(nums); |
| 27 | +backtracking(0,nums,target,newArrayList(),result); |
| 28 | +returnresult; |
| 29 | + } |
| 30 | + |
| 31 | +privatevoidbacktracking(intstart,int[]nums,inttarget,ArrayListtemp, |
| 32 | +List<List<Integer>>result) { |
| 33 | +if(target ==0){ |
| 34 | +List<Integer>newTemp =newArrayList(temp); |
| 35 | +result.add(newTemp); |
| 36 | + }elseif(target >0){ |
| 37 | +for(inti =start;i <nums.length;i++){ |
| 38 | +temp.add(nums[i]); |
| 39 | +backtracking(i,nums,target-nums[i],temp,result); |
| 40 | +temp.remove(temp.size()-1); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | +publicstaticvoidmain(String...strings){ |
| 46 | +CombinationSumIVtest =newCombinationSumIV(); |
| 47 | +int[]nums =newint[]{1,2,3}; |
| 48 | +inttarget =4; |
| 49 | +CommonUtils.printIntegerList(test.combinationSum4_printout(nums,target)); |
| 50 | + } |
| 51 | +} |