Leetcode dfs Combinations, leetcode

Source: Internet
Author: User

Leetcode dfs Combinations, leetcode

Combinations Total Accepted: 18327 Total Submissions: 60479My Submissions

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],]



Given two numbers n and k, all possible combinations of k numbers are given from 1... n.
Train of Thought: dfs
The recursive depth is k, and the j-th node of the I-layer has n-I-j selected branches.
Complexity: time O (n ^ k), Space O (k)

vector<vector<int> > res;int nn, kk;void dfs(int cur, int start, vector<int> &path){if(cur == kk ){res.push_back(path);}for(int i = start; i <= nn; i++){path.push_back(i);dfs(cur + 1, i + 1, path);path.pop_back();}}vector<vector<int> > combine(int n, int k){nn = n, kk = k;vector<int> path;dfs(0, 1, path);return res;}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.