LeetCode[377. Combination Sum IV] 难度[medium]

来源:互联网 发布:文泰刻绘2002解密软件 编辑:程序博客网 时间:2024/06/05 08:18

题目

Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
(Note that different sequences are counted as different combinations.)
大概意思是给出一串数字,找出所有和为targe的排列。

算法思路

这个题目和可重复背包问题有点类似,可以使用动态规划解决。值得注意的地方是这里找的是排列不是组合,所以需要考虑顺序。用一维数组f[i]记录和为i的排列数。由于要考虑顺序,所以内外循环是和重复背包问题反过来,对每个i,都把数字遍历一遍,代表每个数字都有可能是排列的最后一个数。该算法的时间复杂度是O(M*N),M是target,N是数字个数,具体实现如下

class Solution {public:    int combinationSum4(vector<int>& nums, int target) {        int n=nums.size();        vector<int> f(target+1,0);        f[0] = 1;        for(int i=1; i<=target; ++i){            f[i] = 0;            for(int j=0; j<n; ++j)                if(nums[j]<=i)  f[i] += f[i-nums[j]];        }        return f[target];    }};
0 0
原创粉丝点击