惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
Y
Y Combinator Blog
T
Tailwind CSS Blog
G
Google Developers Blog
博客园 - Franky
Google DeepMind News
Google DeepMind News
阮一峰的网络日志
阮一峰的网络日志
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 聂微东
爱范儿
爱范儿
博客园 - 【当耐特】
腾讯CDC
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
H
Help Net Security
C
Check Point Blog
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence
博客园_首页
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

博客园 - 谢绝围观

LeetCode 910. Smallest Range II EAC 抓取CD为AAC文件 Binary Indexed Tree (Fenwick Tree) Lint Code 1365. Minimum Cycle Section UVa 1471 - Defense Lines Windows下安装配置MinGW GCC调试环境 详解LeetCode 137. Single Number II LeetCode 309. Best Time to Buy and Sell Stock with Cooldown LeetCode 84. Largest Rectangle in Histogram 修改注册表删除Windows资源管理器 “通过QQ发送” 右键菜单项 LeetCode 312. Burst Balloons LeetCode 287. Find the Duplicate Number LeetCode 10. Regular Expression Matching LeetCode 117. Populating Next Right Pointers in Each Node II 在Windows Azure VM下搭建SSTP VPN - 谢绝围观 利用.NET Code Contracts实现运行时验证 Log4net 配置实例 解决Windows Server 2012 下利用RRAS创建VPN断线的问题 - 谢绝围观 慎用静态类static class
LintCode 896. Prime Product 简明题解
谢绝围观 · 2018-03-22 · via 博客园 - 谢绝围观

Given a non-repeating prime array arr, and each prime number is used at most once, find all the product without duplicate and sort them from small to large.

Notice
  • 2 <= |arr| <= 9
  • 2 <= arr[i] <= 23

Example

Given arr = [2,3], return [6].

Explanation:
2 * 3 = 6.

Gven arr = [2,3,5], return [6,10,15,30].

Explanation:
2 * 3 = 6, 2 * 5 = 10, 3 * 5 = 15, 2 * 3 *5 = 30

网上的解法用到了位运算和哈希表来避免重复计算。简单说就是用一个int的各个位来表示当前数组各个素数取舍状态。把这个int值从1开始一直加到2^n即可遍历所有状态了。
不足之处是写起来略繁琐。
这个题目其实可以看作自底向上建立一棵二叉树。每处理一个数,可以看作将当前二叉树复制一份,将当前的数字和1分别作为两个子树的父节点。求积也就是把二叉树从根节点到子节点所有路径遍历一遍。
进一步可以看出,这个过程也就是把当前数字和已有的乘积乘一遍而已。
因为素数本身不能算作乘积,因此不能存在结果数组中,所以我们可以单独处理一遍两个素数相乘的情况,同样加入结果集里。

代码:

    vector<int> getPrimeProduct(vector<int> &arr) {
        vector<int> ans;
        for(size_t i = 1; i < arr.size(); i++){
            size_t len = ans.size();
            for(size_t j = 0; j < len; j++){
                ans.emplace_back(arr[i] * ans[j]);
            }
            for(size_t j = 0; j < i; j++){
                ans.emplace_back(arr[j] * arr[i]);
            }
        }
        sort(ans.begin(), ans.end());
        return ans;
    }