美文网首页算法
面试题 16.11. 跳水板

面试题 16.11. 跳水板

作者: 红树_ | 来源:发表于2023-07-15 23:49 被阅读0次

    参考面试题 16.11. 跳水板

    题目

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

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

    输入:
    shorter = 1
    longer = 2
    k = 3
    输出: [3,4,5,6]
    解释:
    可以使用 3 次 shorter,得到结果 3;使用 2 次 shorter 和 1 次 longer,得到结果 4 。以此类推,得到最终结果。
    

    解题思路

    • 枚举:枚举所有情况,若选择i个长木板,则短木板需要有k-i个,而i的范围为0,k

    枚举

    class Solution {
        public int[] divingBoard(int shorter, int longer, int k) {
            if(k == 0) return new int[0];
            if(longer == shorter) return new int[]{longer * k};
            int[] ans = new int[k+1];
            for(int i = 0; i <= k; i++) {
                //选择i个i个longer k-ishorter
                ans[i] = i*longer + (k-i)*shorter;//简化后随i递增不会相同
            }
            return ans;
        }
    }
    

    复杂度分析

    • 时间复杂度:O(k),k为总木板数。
    • 空间复杂度:O(1)

    相关文章

      网友评论

        本文标题:面试题 16.11. 跳水板

        本文链接:https://www.haomeiwen.com/subject/pvpiudtx.html