📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
12
返回列表 发新帖
楼主: tigerbro
跳转到指定楼层
上一主题 下一主题
收起左侧

FB第一轮面试

全局:
  1. public class FBsum {
  2.     public List<List<Integer>> fbSum(int num){
  3.         ArrayList<List<Integer>> rst= new ArrayList<>();
  4.         ArrayList<Integer> path = new ArrayList<>();
  5.         helper(rst,path,num);
  6.         return rst;
  7.     }
  8.     private void helper(ArrayList<List<Integer>> rst, ArrayList<Integer> path, int num) {
  9.         if(num == 0){
  10.             rst.add(new ArrayList(path));
  11.             return;
  12.         }
  13.         int start = 0;
  14.         if(path.size()==0){
  15.             start = 1;
  16.         }else{
  17.             start = path.get(path.size()-1);
  18.         }
  19.         for(int i=start;i<=num;i++){
  20.             path.add(i);
  21.             helper(rst,path,num - i);
  22.             path.remove(path.size()-1);
  23.         }
  24.     }
  25.     public static void main(String[] args) {
  26.         FBsum sol = new FBsum();
  27.         List<List<Integer>> rst = sol.fbSum(4);
  28.         System.out.println(rst.toString());   
  29.     }
  30. }
复制代码

补充内容 (2016-7-31 06:31):
写了个比较容易看懂的dfs。简单试了下,应该没问题。

补充内容 (2016-7-31 06:31):
写了个比较容易看懂的dfs..
回复

使用道具 举报

🔗
wzs9988 2016-7-31 07:01:39 | 只看该作者
全局:
  1. public static void main(String[] args) {
  2.     System.out.println(combination(10));
  3. }
  4. public static List<List<Integer>> combination(int n) {
  5.     List<List<Integer>> res = new ArrayList<>();
  6.     combination(res, new ArrayList<>(), n, 1);
  7.     return res;
  8. }
  9. private static void combination(List<List<Integer>> res, List<Integer> cur, int n, int start) {
  10.     if (n == 0) {
  11.         res.add(new ArrayList<>(cur));
  12.     } else {
  13.         for (int i = start; i <= n; ++i) {
  14.             cur.add(i);
  15.             combination(res, cur, n - i, i);
  16.             cur.remove(cur.size() - 1);
  17.         }
  18.     }
  19. }
复制代码

评分

参与人数 1大米 +5 收起 理由
stephaniede + 5 回答的很好!

查看全部评分

回复

使用道具 举报

🔗
xnature 2016-8-16 07:45:51 | 只看该作者
全局:
short python code

  1. def f(n):
  2.     ans = []
  3.     ret = [[]]
  4.     while True:
  5.         less = filter(lambda x:sum(x) < n, ret)
  6.         eq = filter(lambda x:sum(x) == n, ret)
  7.         ans.extend(eq)
  8.         if less:
  9.             ret = [r + [i] for r in less for i in range(r[-1] if r else n, 0, -1)]
  10.         else:
  11.             return ans
复制代码


还可以优化但是写起来就难看了
回复

使用道具 举报

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

本版积分规则

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