Cover image for Interview Classic 150 Questions P77 Combination

Interview Classic 150 Questions P77 Combination


Timeline

Timeline

2025-11-28

init

Backtracking

Problem:

Note the next starts frompath.back()+1Starting this way avoids duplicates like (1,2),(2,1).

123456789101112131415161718192021222324252627282930
#include <vector>using std::vector;class Solution {private:	vector<vector<int> > res;	void backtrace(vector<int> &path, int n, int k)	{		if (path.size() == k) {			res.push_back(path);			return;		}		int start = path.empty() ? 1 : path.back() + 1;		for (int i = start; i <= n; i++) {			path.push_back(i);			backtrace(path, n, k);			path.pop_back();		}	}public:	vector<vector<int> > combine(int n, int k)	{		res = vector<vector<int> >();		vector<int> path;		backtrace(path, n, k);		return res;	}};
Loading comments…