77. Combinations

Description:

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]


Thought:

一开始想要用之前写的Subsets的代码,求出{1,2,...,n}集合的子集,然后取其中长度为k的集合作为result。结果是没问题的,但是测试显示超出内存了,所以行不通。所以还是需要写算法出来。一个个尝试数字的排列,并选取长度为k的加入到内存中。




Code:

class Solution {
public:
	//eg 4,1 [1][2][3][4]
	//eg 4,2 len = 6 [1,2][1,3][1,4][2,3][2,4][3,4]
	//eg 4,3 [1,2,3] [1,2,4] [1,3,4] [2,3,4]
	vector> combine(int n, int k) {
		if (n < 0 || n < k) return vector>();
		vector> result;
		vector item;
		 helper(n, k, 1, item, result);
		 return result;
	}
	void helper(int n, int k, int start, vector& nums, vector>& result)
	{
		if (nums.size() == k) {
			result.push_back(nums);
			return;
		}
		for (int i = start; i <= n; i++)
		{
			nums.push_back(i);
			helper(n, k, i + 1, nums, result);
			nums.pop_back();
		}
	}
};



你可能感兴趣的:(算法,Algorithms)