Depends on the situation and how you are able to cope with that.
First two important questions:
Are you in an area where people are expected to pass through intermittently, but is deserted the most time?
Are you outside immediate help?
Examples: staircase, parking deck, a road at night. If you answer both questions with Yes and encounter such a person, be very cautious, it could be setup.
If you see or met another person before loitering around for no discernible reasons, it is to 99% a setup. Do not approach, leave the area immediately and hold your mobile ready.
But if you think it is genuine, you can simply ask "Is everything ok/all right?"
Person reacts negatively.
The person moves away from you, turn away their head, shakes their head surly. Then the person knows you are there, but do not want your help and would not appreciate it. Leave.
Person does not react at all or is acting strangely.
Even if you speak louder or carefully touch them on the shoulder, there is no reaction. Or the reaction is quite unnerving: The person seems to be disoriented or acts out of order. In this case which looks like a complete breakdown call the ambulance or ask another person to do that for you. It seems professional help is necessary.
Person reacts neutrally or positively.
So the person knows that you are there and is either observant because (s)he is ashamed or afraid to ask for help or directly invites you to help and listen.
Now it depends on how good you are socially. If you are not so good, simply offer to call help. If you believe you can handle this, speak quietly, simply hold the person (if it is welcomed) and listen attentively. Unfortunately, you will now hear a very sad and stirring story, expect that your clothes will get a little wet. Simply listen and do not try to solve the problem, the person most likely only need someone to vent their grief and frustration and order their thoughts. Normally people are quieting down after a while and get more and more responsive and clear about their situation. They will tell you then if they need some professional help or simply be very thankful and leave you.