|
| 1 | +package medium; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +import utils.CommonUtils; |
| 5 | + |
| 6 | +public class CombinationSumIV { |
| 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 | + public int combinationSum4(int[] nums, int target){ |
| 11 | + Arrays.sort(nums); |
| 12 | + int[] result = new int[target+1]; |
| 13 | + for(int i = 1; i < result.length; i++){ |
| 14 | + for(int n : nums){ |
| 15 | + if(n > target) break; |
| 16 | + else if(n == target) result[i] ++; |
| 17 | + else result[i] += result[i-n]; |
| 18 | + } |
| 19 | + } |
| 20 | + return result[target]; |
| 21 | + } |
| 22 | + |
| 23 | + //this normal backtracking recursive solution will end up in TLE. |
| 24 | + public List<List<Integer>> combinationSum4_printout(int[] nums, int target) { |
| 25 | + List<List<Integer>> result = new ArrayList(); |
| 26 | + Arrays.sort(nums); |
| 27 | + backtracking(0, nums, target, new ArrayList(), result); |
| 28 | + return result; |
| 29 | + } |
| 30 | + |
| 31 | + private void backtracking(int start, int[] nums, int target, ArrayList temp, |
| 32 | + List<List<Integer>> result) { |
| 33 | + if(target == 0){ |
| 34 | + List<Integer> newTemp = new ArrayList(temp); |
| 35 | + result.add(newTemp); |
| 36 | + } else if(target > 0){ |
| 37 | + for(int i = 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 | + public static void main(String...strings){ |
| 46 | + CombinationSumIV test = new CombinationSumIV(); |
| 47 | + int[] nums = new int[]{1,2,3}; |
| 48 | + int target = 4; |
| 49 | + CommonUtils.printIntegerList(test.combinationSum4_printout(nums, target)); |
| 50 | + } |
| 51 | +} |
0 commit comments