-2
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combine(int n, int k) {
    
         List<Integer> list = new ArrayList<>();
         helper(k, n, list, 1);
         return res;
    }
    private void helper(int k, int n, List<Integer> list, int index){
        if(list.size() == k){
            res.add(new ArrayList<>(list));
            return;
        }
        for(int i=index; i<=n; i++){
            list.add(i);
            helper(k, n, list, index+1);
            list.remove(list.size()-1);
        }
        return;
    }
}

When I do this, the output is as follows: [[1,2],[1,3],[1,4],[2,2],[2,3],[2,4],[3,2],[3,3],[3,4],[4,2],[4,3],[4,4]]. And the expected output is: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]].

But when I change this line helper(k, n, list, index+1); to helper(k, n, list, i+1);, the output becomes correct.

I want to know the difference between the two, but so far I'm not getting an answer (isn't it supposed to be the same value every time for both index+1 and i+1?).

1
  • 4
    your for loop increments i, not index. So i and index will have different values. You can observe this by printing i and index above your call to the helper function. Commented Oct 21, 2024 at 21:29

1 Answer 1

1

But when I change this line helper(k, n, list, index+1); to helper(k, n, list, i+1);, the output becomes correct.

As expected.

I want to know the difference between the two, but so far I'm not getting an answer (isn't it supposed to be the same value every time for both index+1 and i+1?).

No it isn't.

The difference is that i is changed in the loop, but not index.

for (int i = index; i <= n; i++) {

means (in English):

"start with i set to the value of index, increment i by one on each iteration, and keep going while i is less or equal to n".

Nothing changes index. In fact index and i will only have the same value on the first iteration.

As the comment says, you can verify this by adding some trace print statements to print out i and index at the start of the loop body.

In Java, = denotes some form of assignment; i.e. i = index means the value of index is assigned to the variable i. It doesn't mean that i and index are the same thing. They were and are two distinct variable. They have the same value immediately after the assignment ... but when i is incremented by the i++ expression the values of the two variables will be different.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.