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

推荐订阅源

博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
The Cloudflare Blog
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园_首页
F
Fortinet All Blogs
J
Java Code Geeks
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog RSS Feed
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
小众软件
小众软件
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队

博客园 - 谢绝围观

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;
    }