Combination Sum IV

来源:互联网 发布:免费qq好友克隆软件 编辑:程序博客网 时间:2024/05/19 18:44

原题链接: https://leetcode.com/problems/combination-sum-iv/description/

原题: 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.

样例:
nums = [1, 2, 3]
target = 4

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.

Solution: 此题可以采用动态规划的解法,用combinations[i]表示用给定数组nums能组成i的方式数量。这样,combinations[0]就应为1,只要我们计算出combinations[target],那么它就是要求的解。

此问题的状态转移可表示为如下形式:
combinations[0] = 1;
combinations[i] = combinations[i - nums[0]] + combinations[i - nums[1]] + … + combinations[i - nums[n]]; 其中,i - nums[j]的大小必须大于等于0;

class Solution {public:    int combinationSum4(vector<int>& nums, int target) {        int n = nums.size();        int combinations[target+1];        combinations[0] = 0;        for (int i = 1; i <= target; i++) {            int sum = 0;            for (int j = 0; j < n; j++) {                if (i - nums[j] > 0) sum += combinations[i - nums[j]];                else if (i - nums[j] == 0) sum += 1;            }            combinations[i] = sum;        }        return combinations[target];    }};

复杂度: 设数组nums的大小为n,那么此算法的时间复杂度为O(n * target),空间复杂度为O(target)。

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 当归的功效与作用 当归 鹦鹉上法庭当证人 归一 磁力引擎搜索 七十二式性态势图 望庐山瀑布 幼儿美术 年轻的护士 炼气五千年 咳嗽吃什么好的快 万古第一帝 狂武神帝 按摩师 西虹市首富 星际工业时代 沈氏家族崛起 问道峨眉 神级狂婿岳风免费全文阅读 岳风柳萱章节目录 山水风景 山楂 加泰罗尼亚 尺码 雪莉尸检结果没有他杀嫌疑 尘落 少年派 飞行少年 波动少女2 暹罗猫 小小的愿望 神道帝尊 两对夫妻换着玩 密熟成桃时在线播放 寄生虫 家庭纶理 做家务的男人 肉嫁高柳家 电信客服电话 秘宝之主