LeetCode 77. Combinations

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

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Example 2:

Input: n = 1, k = 1
Output: [[1]]

Constraints:

1 <= n <= 20
1 <= k <= n

实现思路:

回溯法,只不过每一次要进入下一层的时候要递增+1.

AC代码:

class Solution {
		vector<vector<int>> ans;
		vector<int> sq;
		bool vist[30]= {0};
		void dfs(int idx,int n,int k) {
			if(sq.size()==k) {
				ans.push_back(sq);
				return;
			}
			for(int i=idx+1; i<=n; i++) {
				if(!vist[i]) {
					vist[i]=true;
					sq.push_back(i);
					dfs(i,n,k);
					vist[i]=false;
					sq.pop_back();
				}
			}
		}

	public:
		vector<vector<int>> combine(int n, int k) {
			dfs(0,n,k);
			return ans;
		}
};
上一篇:POJ 1306 Combinations


下一篇:关于 剪枝,autoML