Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 77. Combinations #51

Open
Woodyiiiiiii opened this issue May 21, 2020 · 0 comments
Open

LeetCode 77. Combinations #51

Woodyiiiiiii opened this issue May 21, 2020 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

这题跟46. Permutations很像,使用DFS+回溯法的思想来解。不同的是or循环的初始条件。

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new LinkedList<>();
        if (n < 1 || k < 1 || n < k) return res;
        List<Integer> tmp = new LinkedList<>();
        dfs(res, tmp, n, k, 1);
        return res;
    }
    public void dfs(List<List<Integer>> res, List<Integer> tmp, int n, int k, int start) {
        if (tmp.size() == k) {
            res.add(new LinkedList<>(tmp));
            return;
        }
        for (int i = start; i <= n; ++i) {
            tmp.add(i);
            dfs(res, tmp, n, k, i + 1);
            tmp.remove(tmp.size() - 1);
        }
    }
}

相似题目:

参考资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant