排列组合 - 图1

排列实现

  1. public int arrange(int n, int r) {
  2. if (n < r || n < 0 || r < 0) {
  3. return -1;
  4. }
  5. if (n == r) {
  6. return 1;
  7. }
  8. //从n个不同元素中取r个按序排列
  9. long molecular = 1, denominator = n - r;
  10. int count = n;
  11. while (count > 0) {
  12. molecular *= (count--);
  13. while (denominator > 0 && molecular % denominator == 0) {
  14. molecular /= denominator;
  15. denominator--;
  16. }
  17. }
  18. return (int) molecular;
  19. }

组合实现

  1. public static int combine(int n, int r) {
  2. if (n < r || n < 0 || r < 0) {
  3. return -1;
  4. }
  5. if (n == r) {
  6. return 1;
  7. }
  8. r = Math.min(n - r, r);
  9. //分子
  10. long molecular = 1;
  11. //分母 消去部分分母的乘数个数count 从t开始向下count个
  12. int denominator = r, count = r, t = n;
  13. while (count-- > 0) {
  14. molecular *= (t--);
  15. //计算的时候就进行除法,防止溢出
  16. while (denominator > 0 && molecular % denominator == 0) {
  17. molecular /= denominator;
  18. denominator--;
  19. }
  20. }
  21. return (int) molecular;
  22. }

注意事项

  • 处理溢出,别越界!!!!!!!!