查看: 1807| 回复: 2
跳转到指定楼层
上一主题 下一主题
收起左侧

求问LinkedIn面经题,leetcode 254允许负数的情况

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
https://leetcode.com/problems/factor-combinations/description/

follow up
允许负数的factor和要包含1的组合

以下是我的解法, 可是会有重复的情况,比如 32 的factor有
[1,2,2,2,2,-2]
[1,2,2,2,-2,2]
怎么去重比较好呢?

code:
  1. public static List<List<Integer>> getFactors(int n) {
  2.         List<List<Integer>> result = new LinkedList<List<Integer>>();
  3. //        if (n <= 3) {
  4. //            return result;
  5. //        }
  6.         boolean odd = n < 0 ? true : false;
  7.         List<Integer> list = new LinkedList<Integer>();
  8.         list.add(1);
  9.         helper(result, list, Math.abs(n), 2, 0, odd);
  10.         return result;
  11.     }
  12.     private static void helper(List<List<Integer>> result, List<Integer> list, int n, int start, int negative, boolean odd) {
  13.         if (n == 1) {
  14.             if (list.size() >= 1) {
  15.                 if (odd && negative % 2 == 1 || !odd && negative % 2 == 0) {
  16.                     result.add(new LinkedList<Integer>(list));
  17.                 }
  18.             }
  19.             return;
  20.         }
  21.         for (int i = start; i <= n; i++) {
  22.             if (n % i == 0) {
  23.                 // positive numbers
  24.                 list.add(i);
  25.                 helper(result, list, n / i, i, negative, odd);
  26.                 list.remove(list.size() - 1);
  27.                 //negative numbers
  28.                 list.add(-i);
  29.                 negative++;
  30.                 helper(result, list, n / i, i, negative, odd);
  31.                 negative--;
  32.                 list.remove(list.size() - 1);
  33.             }
  34.         }
  35.     }
复制代码

上一篇:lc已经刷了接近300题,依然完全自主写出medium,什么水平
下一篇:LeetCode刷题 同时上普林斯顿算法课 监督打卡
全局:
你能多写几个例子么。? 比如-12应该怎么分解
回复

使用道具 举报

🔗
水锦鲤 2018-10-27 07:45:28 | 只看该作者
全局:
码一个,好奇如何去重!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表