递归 TLE
class Solution { public: int combinationSum4(vector<int>& nums, int target) { if (target == 0) return 1; int res = 0; for (int n : nums) { if (n <= target) { res += combinationSum4(nums, target - n); } } return res; } };
DP
class Solution { public: int combinationSum4(vector<int>& nums, int target) { vector<int> dp(target+1, 0); dp[0] = 1; sort(nums.begin(), nums.end()); for (int i = 0; i < target; i++) { for (int n : nums) { if (i+n > target) break; dp[i+n] += dp[i]; } } return dp[target]; } };