《程序员面试金典》面试题 16.11. 跳水板

问题描述

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

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

示例:

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

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

代码(递归)

class Solution {
public:
    vector<int> divingBoard(int shorter, int longer, int k) {
        if(!k)return {};
        if(shorter==longer)return {k*shorter};//排除两种特殊情况
        int num = 0,pathsum = 0;
        vector<int> ans;
        set<int> st;
        comp(shorter,longer,k,num,st,pathsum);
        //set<int> st(ans.begin(), ans.end());//利用set为vector去重
        ans.assign(st.begin(), st.end());
        return ans;
    }
    void comp(int &shorter,int &longer,int &k,int num,set<int>&st,int pathsum)
    {
        if(num == k)
        {
            //ans.push_back(pathsum);
            st.insert(pathsum);
            return;
        }
        comp(shorter,longer,k,num+1,st,pathsum+shorter);
        comp(shorter,longer,k,num+1,st,pathsum+longer);
    }
};

结果

超出时间限制

代码

class Solution {
public:
    vector<int> divingBoard(int shorter, int longer, int k) {
        if(!k)return {};
        if(shorter==longer)return {k*shorter};//排除两种特殊情况
        int num = 0,pathsum = 0;
        vector<int> ans;
        for(int i = 0; i <= k; ++i)
        {
            ans.push_back(i*shorter+(k-i)*longer);
        }
        set<int> st(ans.begin(),ans.end());
        ans.assign(st.begin(),st.end());
        return ans;
    }
};

结果

执行用时:260 ms, 在所有 C++ 提交中击败了6.23%的用户
内存消耗:38.7 MB, 在所有 C++ 提交中击败了100.00%的用户

若直接把结果去重

class Solution {
public:
    vector<int> divingBoard(int shorter, int longer, int k) {
        if(!k)return {};
        if(shorter==longer)return {k*shorter};//排除两种特殊情况
        int num = 0,pathsum = 0;
        vector<int> ans;
        set<int> st;
        for(int i = 0; i <= k; ++i)
        {
            st.insert(i*shorter+(k-i)*longer);
        }      
        ans.assign(st.begin(),st.end());
        return ans;
    }
};

结果:

执行用时:272 ms, 在所有 C++ 提交中击败了5.27%的用户
内存消耗:37.2 MB, 在所有 C++ 提交中击败了100.00%的用户

但实际上是不需要去重操作的,原因是考虑以下两种不同的组合:第一种组合,有\(i\)块长木板,则跳水板的长度是\(shorter*(k-i)+longer*i\);第二种组合,有\(j\)块长木板,则跳水板的长度是\(shorter*(k-j)+longer*j\)。其中 \(0 \leq i<j \leq k\)。则两种不同的组合下的跳水板长度之差为:

\[shorter∗(k−i)+longer∗i)−(shorter∗(k−j)+longer∗j)=(longer−shorter)∗(i−j) \]

class Solution {
public:
    vector<int> divingBoard(int shorter, int longer, int k) {
        if(!k)return {};
        if(shorter==longer)return {k*shorter};//排除两种特殊情况
        int num = 0,pathsum = 0;
        vector<int> ans(k+1);
        for(int i = 0; i <= k; ++i)
        {
            ans[i] = (k-i)*shorter+i*longer;//若i*shorter会溢出
        }      
        return ans;
    }
};

结果:

执行用时:20 ms, 在所有 C++ 提交中击败了88.58%的用户
内存消耗:18.7 MB, 在所有 C++ 提交中击败了100.00%的用户
posted @ 2020-07-08 09:51  曲径通霄  阅读(155)  评论(0)    收藏  举报