LeetCode77.组合

    xiaoxiao2022-07-13  165

    力扣(leetcode)77.组合——深搜(DFS)

    原题传送门 题解: 排列组合+dfs:从n个不同的数字中找出k个不同的数字,一共有C(n,k)中情况;这道题需要全排列,用深度优先搜索(dfs)就能搞定。 上代码。

    class Solution { public: int n,k; vector <vector <int>>ans; vector <int>s; void dfs(int x, int y) {//x:放进数组s中的数字,y:当前已经放了几个数。 s.push_back(x); if (y == k) { ans.push_back(s); s.pop_back(); return; } for (int i = x + 1; i <=n; i++) { dfs(i, y + 1); } s.pop_back();//记得删除数组中的数据。 } vector<vector<int>> combine(int a, int b) { n=a; k=b; for (int i = 1; i <= n; i++) { dfs(i, 1); } return ans; } };
    最新回复(0)