leetcode 377 组合之和4

题目:

本质上就是dp里的找零或者解方程问题。

思路:

dp。

代码:

 1 class Solution {
 2     public int combinationSum4(int[] nums, int target) {
 3         int n = nums.length;
 4         if (n == 0) {
 5             return 0;
 6         }
 7         
 8         int[] opt = new int[target + 1];
 9         opt[0] = 1;
10         for (int i = 1; i <= target; i++) {
11             opt[i] = 0;
12             for (int j = 0; j < n; j++) {
13                 if (i >= nums[j]) {
14                     opt[i] += opt[i - nums[j]];
15                 }
16             }
17         }
18         
19         return opt[target];
20     }
21 }

注意事项:

1.初始化,opt[0] = 1;

2.避免数组越界。由于i - nums[j]作为下标,所以需要判断。

猜你喜欢

转载自www.cnblogs.com/hiyashinsu/p/10946898.html