My code:
public class Solution {
private int ret = 0;
public int combinationSum4(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] dp = new int[target + 1];
for (int i = 0; i < nums.length; i++) {
if (nums[i] <= target) {
dp[nums[i]] = 1;
}
}
for (int i = 1; i < dp.length; i++) {
for (int j = 0; j < nums.length; j++) {
int index = i - nums[j];
if (index >= 0) {
dp[i] += dp[index];
}
}
}
return dp[target];
}
}
這道題目也是DP。
然后 dp[i] 表示 target = i 時,需要的次數。
[1, 2, 3] 4
1 2 3 4
0 0 0
將 nums已有的數字反映在 dp[] 上
1 2 3 4
1 1 1
掃描1, 看看之前的數能否通過 [1, 2, 3]到達它。 無
1 2 3 4
1 1 1
掃描 2, 看看之前的數能否通過[1, 2, 3]到達它。有
1 + 1, 所以 dp[2] += dp[2 - 1]
1 2 3 4
1 2 1
掃描3,看看之前的數能否通過[1, 2, 3] 到達它。有
1 + 2, 所以 dp[3] += dp[3 - 2]
2 + 1, 所以 dp[3] += dp[3 - 1]
1 2 3 4
1 2 4
以此類推,可以得到:
dp[4] = 7
然后寫出代碼
其實一開始寫的是 recursion + cache 的做法。
My code:
public class Solution {
private int ret = 0;
public int combinationSum4(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] cache = new int[target + 1];
return helper(0, 0, nums, target, cache);
}
private int helper(int begin, int sum, int[] nums, int target, int[] cache) {
if (begin >= nums.length) {
if (sum == target) {
return 1;
}
else {
return 0;
}
}
else if (sum > target) {
return 0;
}
else if (sum == target) {
return 1;
}
else if (cache[target - sum] != 0) {
return cache[target - sum];
}
else {
int ans = 0;
for (int i = 0; i < nums.length; i++) {
ans += helper(i, sum + nums[i], nums, target, cache);
}
cache[target - sum] = ans;
return ans;
}
}
public static void main(String[] args) {
Solution test = new Solution();
int[] nums = new int[]{3, 33, 333};
int ret = test.combinationSum4(nums, 10000);
System.out.println(ret);
}
}
后來TLE,仔細想想,發現復雜度實在太大了!
即使有cache,也會有大量的stack出現!
所以只能有 Iteration DP來解決。
Anyway, Good luck, Richardo! -- 08/21/2016