[LeetCode]面试题 16.11. 跳水板

题目来源 LeetCode

算法标签 组合数学,递推

题目描述

你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为shorter,长度较长的木板长度为longer。你必须正好使用k块木板。编写一个方法,生成跳水板所有可能的长度。

返回的长度需要从小到大排列。

示例:

输入:
shorter = 1
longer = 2
k = 3
输出: {3,4,5,6}

提示:

0 < shorter <= longer
0 <= k <= 100000

思路

1.暴力搜索
2.对于数量K而言,面对只有两个物体,我们只需要列举尽可能多的 短的数量,然后逐个减少短的数量即可,这个过程方便理解且不需要排序。

题目代码

class Solution {
public:
    vector<int> divingBoard(int shorter, int longer, int k) {
    	if(!k)return {};
        if(shorter == longer)return{k*shorter};//长短相等,则直接给出答案
        vector<int>a(k+1);
        for(int i=0;i<=k;i++)a[i]=shorter*(k-i)+longer*i;
        return a;
    }
};

递归

更新时间4-8:12:41

更新时间4-8:12:11

更新时间4-8:10:18

时间 5.75% 内存 100%

注:
1.思考之后,发现由于参数限制和返回值限制无法做到知用一个函数递归写完。
2.思路从爆搜转向递推公式

思路:
1.公式枚举可能直接放入set去重
3.放入vec数组
4.vec排序

class Solution {
public:
vector<int> ans;
set<int> Set;
    void dfs(int shorter, int longer, int k,int u)
    {
        if(u<0)return;
        int t = shorter*(k-u)+longer*u;
        if(!Set.count(t)&&t)Set.insert(t);
        dfs(shorter,longer,k,u-1);
    }

    vector<int> divingBoard(int shorter, int longer, int k) {
        dfs(shorter,longer,k,k);

        for(auto op:Set)ans.push_back(op);   
        sort(ans.begin(),ans.end());
        return ans;
    }
};
发布了180 篇原创文章 · 获赞 19 · 访问量 5765

猜你喜欢

转载自blog.csdn.net/weixin_43910320/article/details/105378052