LeetCode DAY21(77. Combinations)

Preface

This is a new day to start my backtracking algorithm journey.
Learn something new and keep reviewing what I learnt before.

1. Combinations

LeetCode Link: 77. Combinations
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

Analysis and Solution

Recursion And Backtrack

LeetCode C++ as followings Recursion And Backtrack

class Solution {
private:
    vector<vector<int>> result; // global variation; set that store results that meet the criteria
    vector<int> path; // store sigle result meet the criteria
    void backtracking(int n, int k, int startIndex) {//backtrack with n k and startIndex as parameters; startIndex used to indicate the next recursion; incase repeat combination.
        if (path.size() == k) {//terminate condition; save the path to form combination
            result.push_back(path);//import path to result
            return;
        }
        for (int i = startIndex; i <= n; i++) {//for loop to horizontal traverse
            path.push_back(i); // save i(process path) to path
            backtracking(n, k, i + 1); // recursion vertical traverse; next loop starts at i+1
            path.pop_back(); // backtrack; withdraw the node that was dealed
        }
    }
public:
    vector<vector<int>> combine(int n, int k) {//main function with n k
        result.clear(); // clear result
        path.clear();   // clear path
        backtracking(n, k, 1);//recursion
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值