LeetCode 254. Factor Combinations

本文介绍了一种用于找出整数所有可能的因数组合的算法。该算法递归地寻找每个有效因数,并确保结果中因数序列的升序排列。通过具体实例展示了如何使用此算法来获取输入整数的有效因数分解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Almost the same idea as combinations (permutations)

#include <vector>
#include <iostream>
using namespace std;

/*
  Numbers can be regarded as product of its factor. For example.
  8 = 2 x 2 x 2
    = 2 x 4
  write a function that takes an integer n and return all possible combinations
  of its factor.
  Note:
  1: Each combination's factors must be sorted ascending, for example
     The factors of 2 and 6 is [2, 6], not [6, 2]
  2: You may assume that n is always positive.
  3: Factors should be greater than 1 and less than n.
  
  Example:
  Input: 37, Output: []
  Input: 12, Output: [[2, 6], [2, 2, 3], [3, 4]]
*/
void getFactors(int n, vector<int>& path, vector< vector<int> >& res, int start) {
  if(n == 1 && path.size() > 1) {
    res.push_back(path);
    return;
  }
  for(int i = start; i <= n; ++i) {
    if(n % i == 0) {
      path.push_back(i);
      getFactors(n / i, path, res, i);
      path.pop_back();
    }
  }
}
vector< vector<int> > getFactors(int n) {
  if(n <= 1) return {};
  vector<int> path;
  vector< vector<int> > res;
  getFactors(n, path, res, 2);
  return res;
}

int main(void) {
  vector< vector<int> > res = getFactors(8);
  for(int i = 0; i < res.size(); ++i) {
    for(int j = 0; j < res[i].size(); ++j) {
      cout << res[i][j] << " ";
    }
    cout << endl;
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值