一、题目
二、代码
class Solution
{
public int combinationSum4(int[] nums, int target)
{
int i,j;
int length;
length = nums.length;
int[] dp = new int[target+1];
dp[0] = 1;
// for(i=0;i<length;i++)
// {
// for(j=nums[i];j<=target;j++)
// {
// dp[j] = dp[j]+dp[j-nums[i]];
// }
// }
for(i=0;i<=target;i++)
{
for(j=0;j<length;j++)
{
if(nums[j] <= i)
{
dp[i] = dp[i] + dp[i-nums[j]];
}
}
}
// System.out.println(" "+dp[target]);
return dp[target];
}
}
三、运行结果
四、附录
二刷
class Solution
{
//不追求路径 优先级 动态规划 - 回溯
public int combinationSum4(int[] nums, int target)
{
int i,j;
int[] res = new int[target+1];
int length = nums.length;
res[0] = 1;
for(i=0;i<=target;i++)
{
for(j=0;j<length;j++)
{
if(i<nums[j]) continue;
res[i] = res[i]+res[i-nums[j]];
}
}
return res[target];
}
}