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

算法题求解

全局:

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

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

x
来源于EPIC的OA,具体是列出Permutation(n,m)(n is not equal to m)的所有情况。在网上找了很长时间代码,找到了列出所有combination(n,m) 和 Permutation(n,n)的代码,没找到列Permutation(n,m)的,所以就把这两个组合起来先求combination再对每个combination用permutation。但想想这肯定不是最简单的解法,有大神知道怎么可以一部做出来吗?

上一篇:CTCI Question1.5问题
下一篇:快排的内存都去哪儿了?
🔗
caiqi8877 2014-10-24 04:00:11 | 只看该作者
全局:
好难,真的好难
回复

使用道具 举报

🔗
圆梦梦剧场 2014-10-24 04:22:24 | 只看该作者
全局:
本帖最后由 圆梦梦剧场 于 2014-10-24 04:25 编辑
  1. public class Permutations {
  2.     public ArrayList<ArrayList<Integer>> permute(int[] num, int m) {
  3.         ArrayList<ArrayList<Integer>> permutations = new ArrayList<ArrayList<Integer>>();
  4.         if (num != null && m <= num.length) {
  5.             dfs(num, permutations, new ArrayList<Integer>(), new boolean[num.length], m);
  6.         }
  7.         return permutations;
  8.     }


  9.     private void dfs(int[] num, ArrayList<ArrayList<Integer>> permutations, ArrayList<Integer> permutation, boolean[] used, int m) {
  10.         if (m == permutation.size()) {
  11.             permutations.add(new ArrayList<Integer>(permutation));
  12.             return;
  13.         }

  14.         for (int i = 0; i < used.length; ++i) {
  15.             if (!used[i]) {
  16.                 used[i] = true;
  17.                 permutation.add(num[i]);
  18.                 dfs(num, permutations, permutation, used, m);
  19.                 permutation.remove(permutation.size() - 1);
  20.                 used[i] = false;
  21.             }
  22.         }
  23.     }
  24. }
复制代码
回复

使用道具 举报

🔗
619899442 2014-10-24 19:09:00 | 只看该作者
本楼:
全局:
回溯法。。。
回复

使用道具 举报

🔗
南若冲 2014-10-24 23:59:09 | 只看该作者
本楼:
全局:
试试递归?
回复

使用道具 举报

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

本版积分规则

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